【问题标题】:HTML/CSS/JS: Fix thead when scroll-yHTML/CSS/JS:滚动时修复标题
【发布时间】:2018-02-21 18:11:19
【问题描述】:

如何在 Y 方向滚动时修复完整的头部

请务必注意,表格宽度大于包装 div。所以在 X-Direction 中滚动也应该滚动 thead - 所以我猜想将 thead 与表格分开不是一个选项

请看这个fiddle

HTML

<div>
  <table>
  <thead>
    <tr>
      <th>
        One
      </th>
      <th>
        Two
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        DataOne
      </td>
      <td>
        DatTwo
      </td>
    </tr>
        <tr>
      <td>
        DataOne
      </td>
      <td>
        DatTwo
      </td>
    </tr>
        <tr>
      <td>
        DataOne
      </td>
      <td>
        DatTwo
      </td>
    </tr>
        <tr>
      <td>
        DataOne
      </td>
      <td>
        DatTwo
      </td>
    </tr>
  </tbody>
  </table>
</div>

CSS

div {
  width:80px;
  height:100px;
}
table {
  height:100px;
  display:block;
  overflow:auto;
}

【问题讨论】:

  • 更新了小提琴
  • 希望您尝试自己解决问题,如果遇到特定的编码问题,您可以寻求帮助。这不是免费的编码服务,您的问题太宽泛,因此与网站无关
  • 我不明白这个问题。预期的结果是什么?
  • 预期结果是:垂直滚动,而头部固定在顶部,因此您始终可以看到头部。
  • A small search 给出了有趣的结果...您在搜索时发现了什么?

标签: javascript html css html-table


【解决方案1】:

一种解决方案是使用 javascript 为滚动事件处理程序分配一个函数。使用第二个表格,如果 table1 没有向下滚动,则隐藏 table 2。当 table1 向下滚动时,在 table2 上调用 .show() 。

注意:您需要在 HTML 中包含 JQuery。

HTML

<table id="table-1">
<thead>
    <tr>
        <th>Col1</th>
        <th>Col2</th>
        <th>Col3</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
    <tr>
        <td>info</td>
        <td>info</td>
        <td>info</td>
    </tr>
</tbody>

CSS

body { height: 1000px; }

#header-fixed { 
    position: fixed; 
    top: 0px; display:none;
    background-color:white;
}

Javascript/JQuery

var tableOffset = $("#table-1").offset().top;

var $header = $("#table-1 > thead").clone(); var $fixedHeader = $("#header-fixed").append($header);

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

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

});

小提琴:

http://jsfiddle.net/py8b0s7v/

【讨论】:

  • 你需要设置#header-fixed 有一个固定的位置。请参阅我答案末尾的小提琴中的 CSS。
【解决方案2】:
th{
  position: sticky;
  top: 0;
  background-color:white;
}

嗨, 添加上面的Css。

将位置设置为粘性而不是固定。

Fixed 会将组件“固定”到屏幕顶部,无论它位于页面的哪个位置。 Sticky 使用 JS 计算它在页面上的位置,并且仅在视口到达它时才固定到顶部。简单地说,如果你想在组件上方有内容,就使用sticky。

【讨论】:

    【解决方案3】:

    这为我解决了:

    document.getElementById("TableHead").addEventListener("scroll", function(){
       var translate = "translate(0,"+this.scrollTop+"px)";
       this.querySelector("thead").style.transform = translate;
    });
    

    小提琴:https://jsfiddle.net/pxtokb4g/97/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-25
      • 2017-04-11
      • 2013-08-02
      • 2018-08-15
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多