Javascript 向下滚动页面时,表格标题单元格是否有粘性?

Javascript 向下滚动页面时,表格标题单元格是否有粘性?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,请看一下这个。我试图使表格标题在向下滚动页面时保持在顶部。它没有像我预期的那样工作,因为当标题变得粘稠时,它会改变CSS样式,使它们脱离各自的列。我尝试将填充添加回#sticky.stick>th,但没有任何更改。有什么建议吗 function sticky_relocate() { var window_top = $(window).scrollTop(); var div_top = $('#sticky-anchor').offset().top; if (win

请看一下这个。我试图使表格标题在向下滚动页面时保持在顶部。它没有像我预期的那样工作,因为当标题变得粘稠时,它会改变CSS样式,使它们脱离各自的列。我尝试将填充添加回
#sticky.stick>th
,但没有任何更改。有什么建议吗

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top) {
        $('#sticky').addClass('stick');
    } else {
        $('#sticky').removeClass('stick');
    }
}

$(function () {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});
HTML:


在CSS中进行更改:

.sticky {
    color: #222;
    font-size: 2em;
    display:none;
}
.sticky.stick {
    position:fixed;
    display:inline;
    top: 0;
    z-index: 100;
}
.sticky #comparetable { margin:0; }
这是HTML,基本上你必须创建一个新的表格,表格的标题就在#sticky锚之后,然后把表格放在这个表格之后

<div id="sticky-anchor"></div>
<div class="sticky">
<table id="comparetable" class="blueshine">
<tr>
<td class="blank">&nbsp;</td>                                      
<th>A</th>                                       
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</table>
</div>
<!-- your table goes here -->
<table id="comparetable" class="blueshine">
<tr> <!-- note that the id sticky has been removed -->
<td class="blank">&nbsp;</td>                                      
<th>A</th>                                       
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
<tr>...
希望这有帮助:)

查看此插件
.sticky {
    color: #222;
    font-size: 2em;
    display:none;
}
.sticky.stick {
    position:fixed;
    display:inline;
    top: 0;
    z-index: 100;
}
.sticky #comparetable { margin:0; }
<div id="sticky-anchor"></div>
<div class="sticky">
<table id="comparetable" class="blueshine">
<tr>
<td class="blank">&nbsp;</td>                                      
<th>A</th>                                       
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</table>
</div>
<!-- your table goes here -->
<table id="comparetable" class="blueshine">
<tr> <!-- note that the id sticky has been removed -->
<td class="blank">&nbsp;</td>                                      
<th>A</th>                                       
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
<tr>...
function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top) {
        $('.sticky').addClass('stick');
    } else {
        $('.sticky').removeClass('stick');
    }
}