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>

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

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

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

相关文章:

javascript - jquery-1.10.2.js :1472 Uncaught Error: Syntax error, 无法识别的表达式 : label[for ='team[]' ], 标签[for ='team[]'] *, #team[]-error

javascript - ajax post数据错误返回数据1而不是0

html - 在 HTML5 中使用 H1 Logo

python - 在Python中使用BeautifulSoup提取表标签值?

html - 具有多列的 HTML 表格的设计

html - css网格如何在行之间添加线?

javascript - 根据 jQuery 中多个实例的另一个元素高度设置高度

jquery - 禁用 jQuery UI Datepicker 中除周日之外的所有周日

html - 悬停时不会触发 CSS3 过渡

html - 使用 css 缩放字体是否宽度或高度改变