我想设计一个HTML表格,当用户将其滚动到视野之外时,并且只有当用户将其滚动到视野之外时,表头才会停留在页面的顶部。 例如,表格可能在页面下方500像素处,我怎样才能使它在用户将表头滚动到视野之外时(浏览器检测到它不再在窗口视野中),它能保持在顶部? 有谁能给我一个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>
在它离开视图时与页面一起滚动。
重要的是:我不是在寻找一个解决方案,即<tbody>
将有一个滚动条(溢出:自动)。
你可以这样做,在 "window "上接入 "scroll "事件处理程序,并使用另一个固定位置的 "table "来显示页面顶部的标题。
HTML:
<table id="header-fixed"></table>
CSS:
#header-fixed {
position: fixed;
top: 0px; display:none;
background-color:white;
}
JavaScript:
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();
}
});
当用户向下滚动到足以隐藏原来的表头时,这将显示表头。 当用户再次向上滚动页面时,它将再次隐藏。
工作实例:
好吧,我正试图获得同样的效果,而不求助于固定尺寸的列或对整个表格有固定的高度。
我想出的解决方案是一个黑客。它包括复制整个表格,然后隐藏所有东西,除了标题,并使其有一个固定的位置。
<div id="table-container">
<table id="maintable">
<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>some really long line here instead</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>
<tr>
<td>info</td>
<td>info</td>
<td>info</td>
</tr>
<tr>
<td>info</td>
<td>info</td>
<td>info</td>
</tr>
</tbody>
</table>
<div id="bottom_anchor"></div>
</div>
body { height: 1000px; }
thead{
background-color:white;
}
function moveScroll(){
var scroll = $(window).scrollTop();
var anchor_top = $("#maintable").offset().top;
var anchor_bottom = $("#bottom_anchor").offset().top;
if (scroll>anchor_top && scroll<anchor_bottom) {
clone_table = $("#clone");
if(clone_table.length == 0){
clone_table = $("#maintable").clone();
clone_table.attr('id', 'clone');
clone_table.css({position:'fixed',
'pointer-events': 'none',
top:0});
clone_table.width($("#maintable").width());
$("#table-container").append(clone_table);
$("#clone").css({visibility:'hidden'});
$("#clone thead").css({'visibility':'visible','pointer-events':'auto'});
}
} else {
$("#clone").remove();
}
}
$(window).scroll(moveScroll);
请看这里:
编辑:更新了代码,使标题可以接收指针事件(所以标题中的按钮和链接仍然有效)。这解决了luhfluh和Joe M.报告的问题。
新的jsfiddle在这里:http://jsfiddle.net/cjKEx/
我已经能够解决改变列宽的问题了。 我从安德鲁的上述解决方案开始(非常感谢!),然后添加了一个小循环来设置克隆的td的宽度。
$("#header-fixed td").each(function(index){
var index2 = index;
$(this).width(function(index2){
return $("#table-1 td").eq(index).width();
});
});
这就解决了问题,而不需要克隆整个表格并隐藏主体。 我是JavaScript和jQuery的新手(也是堆栈溢出的新手),所以感谢任何意见。