即使在滚动之后,也要固定表格标题的位置


make position of table heading fixed even after scrolling

我有一个带有垂直滚动条的表格

<div id="div_data" style="top: 7px;">
<table id="data" cellspacing="0" cellpadding="0">
            <thead>
              <tr class="fix"><td class="newClass"> <div> Algebra </div></td>
                   <td class="newClass"><div> Geometry</div></td>
                   <td class="newClass"><div> Theorems</div></td> 
                   <td class="newClass"><div> Comment</div></td>
                   </tr>
            </thead>
            <tbody style="overflow:auto; height:100px;">
            ......................
            </tbody>
    </table>
        <table id="header-fixed" cellspacing="0" cellpadding="0"></table> 
    </div>      

当我滚动#data table时,我需要在不滚动的情况下固定表标题元素。为此,我做了以下jquery代码:

var tableOffset = $("#data").offset().top;
var $header = $("#data > thead").clone();
var $fixedHeader = $("#header-fixed").append($header);  
    $("#div_data").scroll(function(){ 
        $('#div_row_headers').scrollTop($('#div_data').scrollTop()); 
         var offset = $(this).scrollTop();
        if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
            $fixedHeader.show();
        }
        else if (offset < tableOffset) {
            $fixedHeader.hide();
        } 
    });

第一个表的元素中的内容被克隆到第二个表中,但#header-fixed表的位置不在第一个表中的标题区域上。它在桌子中间。我只想把它叠加在#data table.我的css如下:

#header-fixed { 
position: fixed; 
display:none;
background-color:white;
}
table#header-fixed tr td {
    width: 155px;
}       
table#header-fixed tr td div {
    width: 155px;
    float: left;
    text-align: center;
}   

编辑:当我滚动窗口滚动条时,新表格是固定的,我需要滚动表格,当我滚动窗滚动条

您唯一要做的就是使用tbody标记包装您的表体。并将以下css应用于该标记。

 tbody {
    display: block;
    height: 100px;
    overflow: auto;        
    width: 100%;
}