当用户使用 jQuery 将其滚动到视图之外时,表头保持固定在顶部 [英] Table header to stay fixed at the top when user scrolls it out of view with jQuery
问题描述
我正在尝试设计一个 HTML 表格,当且仅当用户将其滚动到视图之外时,其中的标题将保留在页面顶部.例如,表格可能距页面向下 500 像素,我该如何制作,以便如果用户将标题滚动到视图之外(浏览器检测到它不再以某种方式出现在 Windows 视图中),它将保持在顶部?任何人都可以给我一个 Javascript 解决方案吗?
I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500 pixels down from the page, how do I make it so that if the user scrolls the header out of view (browser detects its no longer in the windows view somehow), it will stay put at the top? Anyone can give me a Javascript solution to this?
<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>
因此,在上面的示例中,我希望 So in the above example, I want the 重要提示:我不正在寻找一种解决方案,其中 IMPORTANT: I am NOT looking for a solution where the 您可以通过点击 You would do something like this by tapping into the HTML: CSS: JavaScript: 当用户向下滚动到足以隐藏原始表头时,这将显示表头.当用户再次向上滚动页面时,它将再次隐藏. This will show the table head when the user scrolls down far enough to hide the original table head. It will hide again when the user has scrolled the page up far enough again. 工作示例:http://jsfiddle.net/andrewwhitaker/fj8wM/ 这篇关于当用户使用 jQuery 将其滚动到视图之外时,表头保持固定在顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 在页面消失时随页面滚动.
<thead>
to scroll with the page if it goes out of view. 将有一个滚动条(溢出:自动).
<tbody>
will have a scrollbar (overflow:auto).推荐答案
window
上的 scroll
事件处理程序,并使用另一个table
具有固定位置以在页面顶部显示标题.scroll
event handler on window
, and using another table
with a fixed position to show the header at the top of the page.<table id="header-fixed"></table>
#header-fixed {
position: fixed;
top: 0px; display:none;
background-color:white;
}
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();
}
});
登录
关闭