10
09/2014
bootstrap table header fixed
原理
<div class="outerDIV">
<div class="innerDIV">
<table></table>
</div>
</div>
// fixed header table
.tbOuterDiv {
position: relative;
padding-top: 37px; //height of your thead
}
.tbInnerDiv {
overflow-y: auto;
height: 200px; //the actual scrolling container
}
table.fixedHeader thead {
display: block;
position: absolute;
top: 0;
left: 0;
}
这样就可以把 thead 固定,而 tabke 翻滚了。下一步,就是要把 th 的宽度用 js 动态处理了!(保持列宽度上下一致)
function scrollingTableSetThWidth(tableId)
{
var table = document.getElementById(tableId);
ths = table.getElementsByTagName('th');
tds = table.getElementsByTagName('td');
if(ths.length > 0) {
for(i=0; i < ths.length; i++) {
tds[i].style.width = getCurrentComputedStyle(ths[i], 'width');
}
}
}
function getCurrentComputedStyle(element, attribute)
{
var attributeValue;
if (window.getComputedStyle)
{ // class A browsers
var styledeclaration = document.defaultView.getComputedStyle(element, null);
attributeValue = styledeclaration.getPropertyValue(attribute);
} else if (element.currentStyle) { // IE
attributeValue = element.currentStyle[vclToCamelCases(attribute)];
}
return attributeValue;
}
如果有 jquery 的话
jQuery(function(){
//////
$('.fixedHeader').each(function(){
$(this).wrap('<div class="tbOuterDiv"></div>').wrap('<div class="tbInnerDiv"></div>');
scrollingTableSetThWidth($(this));
})
var lasyResize=null;
$(window).on('resize',function(){
clearInterval(lasyResize);
lasyResize=setTimeout(function(){
$('.fixedHeader').each(function(){
scrollingTableSetThWidth($(this));
})
},200)
})
//////
})
function scrollingTableSetThWidth(table) {
var firstRow=table.find('tbody tr:first');
table.find('thead th').each(function(j,k){
$(k).css({width:firstRow.find('td:eq('+j+')').outerWidth()+'px'})
})
outerWidth 拿到包括 padding 的宽度;除了 opera 所有浏览器的 resize 重复触发多次。所以加上 lasy。