利用js+css+html实现固定table的列头不动
话不多说,跟这小编来一起看下吧
1、CSS
<styletype="text/css"> #scroll_head{ position:absolute; display:none; } </style>
2、Javascript
<scripttype="text/javascript"> //该函数在上面一个table数据加载完成后调用 //把表头的宽度设置到会滚动的页头去 varcopyWidth=function(){ varb=$('#data_tbody').prev().find('tr:last').find('th'); varc=$('#scroll_head').find('tr:last').find('th'); for(vari=0;i<b.length;i++){ varnewWith=b.eq(i).width(); if($.browser.msie){ newWith+=1; } c.eq(i).width(newWith); } } $(function(){ $(window).scroll(function(){ if($('#data_tbody').length>0){ varthead=$('#data_tbody').prev(); varthOffset=thead.offset(); varscTop=$(window).scrollTop();//滚动条相对top的位置 if(scTop>thOffset.top){//滚动条滚到thead及以下的位置,用临时的thead代替显示 $('#scroll_head').css('display','block'); $('#scroll_head').offset({top:scTop,left:thOffset.left}); } else{//滚动条滚到thead上的位置,用table的原始thead显示 $('#scroll_head').css('display','none'); } } }); }); </script>
3、Html内容
<divid="data_div"> <table> @*thead内容及样式同scroll_head中的thead*@ @*thead使用深背景色,避免滚动时和tbody内容重叠显示*@ <thead> <tr> @*一级标题*@ <thclass="tt1"colspan="2">一级1</th> <thclass="tt2"colspan="5">一级2</th> <thclass="tt3"colspan="6">一级3</th> </tr> <tr> @*二级标题*@ <thstyle="width:23px;">二级11</th> <thstyle="width:36px;">二级12</th> <thclass="tt"style="width:40px;">二级21</th> <thclass="tt"style="width:30px;">二级22</th> <thclass="tt"style="width:30px;">二级23</th> <thclass="tt"style="width:30px;">二级23</th> <thclass="tt"style="width:30px;">二级24</th> <thclass="tt"style="width:30px;">二级25</th> <thclass="tt"style="width:30px;">二级31</th> <thclass="tt"style="width:30px;">二级32</th> <thclass="tt"style="width:30px;">二级33</th> <thclass="tt"style="width:30px;">二级33</th> <thclass="tt"style="width:30px;">二级34</th> <thclass="tt"style="width:30px;">二级35</th> <thclass="tt"style="width:30px;">二级36</th> </tr> </thead> <tbodyid="data_tbody"> 数据内容,在数据加载完成后调用copyWidth()函数解决兼容性 </tbody> </table> </div> <divid="scroll_head"style="display:block;top:168px;left:0px;position:relative;"> <tablewidth="100%"> <thead>@*thead使用深背景色,避免滚动时和tbody内容重叠显示*@ <tr> @*一级标题*@ <thclass="tt1"colspan="2">一级1</th> <thclass="tt2"colspan="5">一级2</th> <thclass="tt3"colspan="6">一级3</th> </tr> <tr> @*二级标题*@ <thstyle="width:23px;">二级11</th> <thstyle="width:36px;">二级12</th> <thclass="tt"style="width:40px;">二级21</th> <thclass="tt"style="width:30px;">二级22</th> <thclass="tt"style="width:30px;">二级23</th> <thclass="tt"style="width:30px;">二级23</th> <thclass="tt"style="width:30px;">二级24</th> <thclass="tt"style="width:30px;">二级25</th> <thclass="tt"style="width:30px;">二级31</th> <thclass="tt"style="width:30px;">二级32</th> <thclass="tt"style="width:30px;">二级33</th> <thclass="tt"style="width:30px;">二级33</th> <thclass="tt"style="width:30px;">二级34</th> <thclass="tt"style="width:30px;">二级35</th> <thclass="tt"style="width:30px;">二级36</th> </tr> </thead> </table> </div>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,同时也希望多多支持毛票票!