1. 程式人生 > >bootstrap table 實現固定懸浮table 表頭並可以水平滾動

bootstrap table 實現固定懸浮table 表頭並可以水平滾動

app 實現 question get net width class pan eight

在開發項目中,需要將表格頭部固定,而且表格大多數情況下是會水平滾動的。項目的css框架是bootstrap 3,故也可以叫做bootstrap table。

需要實現的是:表格頭部固定,並且支持水平滾動

html code(source table):

<table id="top_fix_table" border="0" cellpadding="4" cellspacing="0" class="table table-hover">
    <thead>
        <tr id="table_head">
             <
td>Test</td> .... </tr> </thead> <tbody> </tbody> </table>

stylesheet code:

#fixed_table #fix_head{
    background: #FFFFFF;
    box-shadow: 0px 0px 5px #888888;
}

Javascript code:

<script type="text/javascript">
$(
function(){ var sourceTable = $("#top_fix_table");//table id var sourceTableHead = $("#table_head");//table thead tr id var headHeight = sourceTableHead.height();//table thead tr height var sourceTableWidth = sourceTable.outerWidth(); //get source table width //copy table and thead html tag from source table,
$(‘body‘).append(‘<div id="shelter"><table id="fixed_table" border="0" cellpadding="4" cellspacing="0" class="table table-hover"><thead></thead></table></div>‘); //only set top and left,beacuse i need the top bar can scroll left $("#shelter").css({‘height‘:headHeight,‘position‘:‘fixed‘,‘top‘:‘0‘,‘left‘:‘0‘}); //set target table width equal source table width $("#fixed_table").css({‘width‘:sourceTableWidth+"px"}); //only clone tr html and change thead tr id attr var targetHead = sourceTableHead.clone().attr(‘id‘,‘fix_head‘); targetHead.appendTo(‘#fixed_table thead‘); //mark target table thead td width,height equal source table thead td width,height $("#table_head td").each(function(index,value){ var tempWidth = $(value).outerWidth(); var tempHeight = $(value).outerHeight(); $("#fixed_table td").eq(index).css({‘width‘:tempWidth+"px",‘height‘:tempHeight+"px"}); }); $(window).scroll(function(){ //scroll left method var sl=-Math.max($(‘body‘).scrollLeft(),$(‘document‘).scrollLeft()); $(‘#shelter‘).css("left",sl+‘px‘); var scroll_top = $(‘body‘).scrollTop() - sourceTable.offset().top; //control show or hide if (scroll_top > 0) { $(‘#shelter‘).show(); }else { $(‘#shelter‘).hide(); } }); }); </script>

參考文檔:

  1. css position:fixed時還能水平滾動,如何實現 實現了固定頭部的水平滾動
  2. 網頁制作中在頭部固定懸浮table表頭(thead)的方法 javascript 主要代碼來源
  3. jquery outerHeight方法 outerWidth方法 獲取元素實際寬度高度 學習獲取元素實際寬度

bootstrap table 實現固定懸浮table 表頭並可以水平滾動