jquery - 当用户使用 jQuery 将表头滚动到 View 之外时,表头保持固定在顶部

标签 jquery html html-table

我正在尝试设计一个 HTML 表格,当且仅当用户将其滚动到 View 之外时,标题才会保留在页面顶部。例如,表格可能比页面向下 500 像素,如果用户将标题滚动到 View 之外(浏览器以某种方式检测到它不再在 Windows View 中),我该如何做到这一点,它会保持在顶部?谁能给我一个 Javascript 解决方案?

<table>
  <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>
</table>

所以在上面的例子中,我想要 <thead>如果页面超出 View ,则滚动页面。

重要提示:我不是在寻找<tbody>将有一个滚动条(溢出:自动)。

最佳答案

您可以通过点击 window 上的 scroll 事件处理程序来执行类似的操作,并使用另一个具有固定位置的 table 来显示页面顶部的标题。

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

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

  if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
    $fixedHeader.show();
  } else if (offset < tableOffset) {
    $fixedHeader.hide();
  }
});
#header-fixed {
  position: fixed;
  top: 0px;
  display: none;
  background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
</table>
<table id="header-fixed"></table>

当用户向下滚动到足以隐藏原始表头时,这将显示表头。当用户再次向上滚动页面足够远时,它将再次隐藏。

工作示例:http://jsfiddle.net/andrewwhitaker/fj8wM/

关于jquery - 当用户使用 jQuery 将表头滚动到 View 之外时,表头保持固定在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709390/

相关文章:

javascript - Ajax 延迟不起作用

javascript - 在 ASPX 页面上使用多个 JavaScript 脚本

javascript - 如何使用 jQuery 将数字添加到输入字段中的当前数字?

html - 使用 DIV 而不是 TABLE,但 DIV 宽度未填充可用空间

ruby-on-rails - Rails 链接表belongs_to 或has_many 不起作用

javascript - 将主窗口标题更改为 iframe 标题

javascript - 从 Javascript 中的文本区域中删除某些文本

javascript - 如何在书写时将表情符号字符串转换为其图标?

css - "Hard"html/css 中的单词中断/拆分

javascript - 使用 AngularJS 尝试在中间插入一个 <tr>