如何在不使用任何其他jQuery插件的情况下创建带有冻结标题的简单可滚动表行?
[我找到了一些使用jQuery插件的解决方案,例如fixedheadertable,chromatable等,但我只想在jQuery中使用“ pure”库。
基本上隐藏在主体顶部具有固定位置的空表/ tr外壳。创建一个函数以遍历数据表的第一行并捕获width和innerHTML。在pageload上调用该函数,使其准备就绪。捕获从屏幕顶部到数据表顶部的距离。当页面滚动到该点时,切换显示/隐藏表格。当窗口调整大小以重新填充固定表/ tr shell时,也会捕获。...
<script type="text/javascript">
var distance = 0, $window = $(window);
function resizeHdr(){
$("#tblHoldHdr").css("width", $("#tblData").css("width"));
var oTr=$("#trHoldHdr").html("");//short var for frozen header row
$("#tblData tr:first").find("th").each(function(i){//loop through header to mimic
oTr.append('<th style="width:'+$(this).css("width")+' !important">'+$(this).html()+'</th>');//copy content with forced width
});
}
$(function(){
distance=$('#tblData').offset().top;
$("#tblHoldHdr").css({"margin-left":$("body").css("margin"),"margin-top":-parseInt($("body").css("margin"))+"px"});//position frozen hder
resizeHdr();
});
$(window).scroll(function(){
$("#tblHoldHdr").css("left", -$(this).scrollLeft());//frozen hdr pos fixed doesn't move w/ scrolling so this keeps it lined up (w/o "-" header slides twice as fast out to the right)
if($window.scrollTop() >= distance){
$("#tblHoldHdr").css("display","");// Hdr has reached the top
}else{
$("#tblHoldHdr").css("display","none");// Hdr below top
}
});
$(window).resize(function(){
resizeHdr();
});
</script>
<!-- At the top goes this is the frozen header table - populated by jQ on doc.ready() -->
<table style="display:none;position:fixed;" id="tblHoldHdr">
<tr id="trHoldHdr"></tr>
</table>
…other html code…
<!-- This is the data output table wherever you need it on the page -->
<table id="tblData"><thead>
<tr><th> Col 1</th><th>Col 2</th></tr>
<tr><td> Data 1/1</td><td>Data 1/2</td></tr>
<tr><td> Data 2/1</td><td>Data 2/2</td></tr>
</table>
我从很多人那里借来了如何捕获滚动和窗口大小的信息。我最初只给固定表/ tr填充一次,然后应用大小即可,但是Chrome可以工作,但后来却没有。可能会有其他人使用魔术枣来使该简单方法起作用。
这里是滚动同步的演示
https://jsfiddle.net/RaviMakwana/28fgaut5/
var div1 = document.getElementById("scrollDiv1");
var div2 = document.getElementById("scrollDiv2");
div2.addEventListener("scroll", function(){
div1.scrollLeft = this.scrollLeft;
})
<div id="scrollDiv1" style="height: 100px;overflow:hidden;">
<div style="width:1000px;">
Test 1 321321 131 313 1321 33 13
</div>
</div>
<div id="scrollDiv2" style="height: 100px;overflow:scroll;">
<div style="width:1000px;">
Test 2 23232
</div>
</div>