html固定table表头的实现思路
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
?
?實(shí)現(xiàn)步驟
1.將table放在可滾動容器中;
2.可滾動容器外層還需要一個(gè)容器,這個(gè)容器需設(shè)置超出范圍隱藏和定位(相對、絕對都行);
3.利用腳本克隆一個(gè)目標(biāo)table,調(diào)整克隆table的列寬與原table相同,隱藏tbody,追加到外層的容器中;
4.監(jiān)聽滾動容器的滾動事件,動態(tài)調(diào)整克隆table的左偏移,上偏移不需要調(diào)整,因?yàn)橐呀?jīng)固定了。
效果演示
<html>
<head>
<style>
? ? .tablebox{height:300px;overflow:auto;width:100%;}
? ? .tableboxcontainer table td{white-space:nowrap;}
? ???.tableboxcontainer table thead{background:#ddd;}
? ? .tableboxcontainer{position:relative;width:300px;overflow:hidden;}
</style>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="tableboxcontainer">
<div class="tablebox" id="tablebox">
? ? <table class="table">
? ?? ???<thead>
? ?? ?? ?? ?<tr>
? ?? ?? ?? ?? ? <td>列1</td><td>列2</td><td>列3</td><td>列4</td><td>列5</td>
? ?? ?? ?? ?? ? <td>列6</td><td>列7</td><td>列8</td><td>列9</td><td>列10</td>
? ?? ?? ?? ?</tr>
? ?? ???</thead>
? ?? ???<tbody>
? ?? ?? ?? ?
? ?? ???</tbody>
? ? </table>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
? ? $(function(){
? ?? ???//生成表格測試數(shù)據(jù)
? ?? ???var $table=$("#tablebox").find("table");
? ?? ???var $tbody=$table.find("tbody");
? ?? ???for(var i=0;i<20;i++){
? ?? ?? ?? ?var $tr=$("<tr>");
? ?? ?? ?? ?for(var j=0;j<10;j++){
? ?? ?? ?? ?? ? $tr.append(function(){
? ?? ?? ?? ?? ?? ???return $("<td>").text("行:"+(i+1)+"列:"+(j+1));
? ?? ?? ?? ?? ? });
? ?? ?? ?? ?}
? ?? ?? ?? ?$tr.appendTo($tbody);
? ?? ???}
? ?? ???//克隆原表,追加到最外層容器中
? ?? ???var $table_fixed=$table.clone();
? ?? ???var colwidths=[];
? ?? ? //設(shè)置克隆表的列寬
? ?? ???$tbody.find("tr:eq(0)").find("td").each(function(){
? ?? ?? ?? ? var width=$(this).width()+parseFloat($(this).css("padding-left"))+parseFloat($(this).css("padding-right"));
? ?? ?? ?? ? colwidths.push(width);
? ?? ? });
? ?? ?? ? $table_fixed.find("thead td").each(function(i){
? ?? ?? ?? ?$(this).width(colwidths);
? ?? ? });
? ?? ???$table_fixed.css({"position":"absolute","left":0,"top":0,"table-layout":"fixed"});
? ?? ???$table_fixed.find("tbody").hide();//隱藏克隆表的tbody
? ?? ???$("#tablebox").parent().append($table_fixed);
? ?? ???//監(jiān)聽原表容器的滾動事件
? ?? ???$("#tablebox").bind("scroll",function(){
? ?? ?? ?? ?var left=$(this).scrollLeft();
? ?? ?? ?? ?$table_fixed.css({"left":-left});
? ?? ???});
? ? });
</script>
</body>
</html>
WEB前端互動交流群 434623999
轉(zhuǎn)載于:https://my.oschina.net/u/3709170/blog/1593269
總結(jié)
以上是生活随笔為你收集整理的html固定table表头的实现思路的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用系统滚动条实现NumericUpDow
- 下一篇: Jackson反序列化提示:Can no