【问题标题】:How to keep the header fixed when scrolling through data滚动数据时如何保持标题固定
【发布时间】:2018-03-16 02:09:32
【问题描述】:

我有两个表,第一个用作使用 datepicker 的搜索功能,第二个包含 theadtbody,其中包含我的数据的实际标题和行。我试过关注http://jsfiddle.net/wLcjh/255/

var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead");
var $fixedHeader = $("#header-fixed").append($header.clone());
console.log(tableOffset);
console.log($header);
console.log($fixedHeader);
console.log($fixedHeader.is(":hidden"));

$(window).bind("scroll", function () {
    var offset = $(this).scrollTop();

    if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
        $fixedHeader.show();

        $.each($header.find('#tr1 > th'), function (ind, val) {
            var original_width = $(val).width();
            $($fixedHeader.find('#tr1 > th')[ind]).width(original_width);
        });
    }

});

但是,它对我的​​页面没有任何影响。有没有可能实现?

【问题讨论】:

  • 您可以尝试使用数据表插件datatables.net, datatables.net/extensions/fixedheader
  • 执行此操作的标准方法是将标题放在一个单独的表中,该表是固定的,并让数据表在其后面滚动并隐藏溢出。
  • 你的 Fiddle 似乎在工作......
  • @LouysPatriceBessette 抱歉,我不清楚,这是我要使用的示例,我的实际代码并不那么简单,实际表格周围还有更多 div。
  • @nurdyguy 你能再扩大一点吗,我会把溢出放在哪里?那是给thead还是tbody?固定,您的意思是为标题表设置位置固定?不过还是谢谢你的帮助

标签: javascript jquery html css


【解决方案1】:

使用postion:sticky 使用纯 CSS 来做这件事怎么样?

body { height: 1000px; }
thead tr th{
    background: white;
    position: sticky;
    top: 0;
  }
<table id="table-1">
    <thead id="header-fixed">
        <tr>
            <th >Col1</th>
            <th >Col2</th>
            <th >Col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>info000000</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>infolllllllllllll</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info00000000</td>
        </tr>
    </tbody>
</table>

【讨论】:

  • 效果很好,谢谢。我以前从未使用过或见过。谢谢你!为我节省了很多压力时间:)
  • @goldenBoy 好的!如果对您有帮助,标记为答案是一个好习惯:)
  • 它适用于 chrome.. 但遗憾的是仍然不支持 firefox。这就是为什么我还没有标记为已回答。似乎这对于周围的其他人来说一直是一个长期存在的问题:sticky
  • @goldenBoy 很公平。我在这里运行 Firefox beta 频道,如果有任何安慰,您提到的问题在 FF59+ 中已修复。如果您希望支持旧版本的 Firefox,也许您可​​以尝试一些解决方法stackoverflow.com/questions/37071535/…
【解决方案2】:

您可以在标题容器上应用position: fixed; CSS 以保持位置固定。

请检查以下代码::

.header-container-fixed {
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
    width: 100%;
    z-index: 1;
}

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 2015-10-19
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多