【发布时间】:2014-02-28 13:43:12
【问题描述】:
我有一个 HTML 表格,其中有很多不适合屏幕的标题。由于行的数量,我使用了一个粘性标题,它以垂直方式完美运行。
不幸的是,它在水平滚动时也保持了粘性。我应该如何更改我的代码以允许水平滚动但保持垂直滚动的固定标题?
表格本身很简单:
<table id="calctable">
<thead class="fixed">
<tr id="table-head">
<th><!--Loads of them--></th><th><!--Continues like forever--></th>
</tr>
</thead>
<tbody>
<tr><td><!--And even more of this kind...--></td></tr>
<tr><td><!--And even more of this kind...--></td></tr>
</tbody>
</table>
<table id="header-fixed"></table>
还有我的 Javascript(有效,但是……只能在垂直滚动中使用):
$(function() {
var tableOffset = $("#calctable").offset().top;
var $header = $("#calctable > 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();
}
});
});
还有我的 CSS:
#header-fixed {
position: fixed;
top: 0px; display:none;
background-color:white;
}
谢谢!
【问题讨论】:
-
我前段时间遇到过这个问题:mkoryak.github.io/floatThead 是解决这个问题的好插件。它唯一的问题是它在标题元素容器上强制使用
overflow:hidden;。因此,如果您想在标题中包含 CSS 下拉列表等,您需要将它们设置为position:fixed。但这是一个非常特殊的用例。
标签: javascript jquery html css tableheader