js、css实现table表头固定

    xiaoxiao2021-03-25  122

    原生table表头随表体一起上下滚动 在html中利用js、css将表头固定,可将原table拆分,分为表头table,表体table。 大致框架如:

    <!--整体table--> <table> <tr> <td> <!--表头table--> <table> <!--只存放表头--> <th></th> <th></th> </table> </td> </tr> <tr> <td> <!--表体table--> <table> <!--存放表数据--> <tr> <td></td> </tr> <tr> <td></td> </tr> </table> </td> </tr> </table>

    但是,这种情况适合没有滚动条的情况,一旦出现滚动条,则表头和表体会有偏离。因此,我们可以在开始的时候根据滚动条的宽度来用css设置表头的偏离位置。 代码如下:

    <html> <head> <title> </title> <style> .table th,.table td{ min-width:60px; } table{ empty-cells:show; border-collapse: collapse; margin:0 auto; } .scrolltable{overflow-x:hidden; overflow-y: scroll; width: 100%;} </style> </head> <body> <!--fixed thead begin--> <div style="margin-left: 10px; margin-right:0px; overflow-x: auto;"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <div style="margin-left:10px;"> <table align="center" border="0" style="font-size: 12px; margin-left: 0px; margin-bottom: 0px; margin-right: 16px;" id="table1" class="table table-bordered table-striped table-hover"> <tr> <!-- 这里存放表头名称,例如: <th >用户号</th> --> </tr> </table> </div> </td> </tr> <tr> <td align="center" width="100%"> <div style="overflow-y: auto;margin-left:0px;" align="center" class="scrolltable"> <table class="table table-bordered table-striped table-hover" id="searchresult" style="font-size: 12px"> <thead id="thead" style="display: none;"></thead> <!-- 这里存放列表内容(后台获取的值 datalist) <tr> <td></td> </tr> 例如 --> </table> </div> </td> </tr> </table> </div> <!--fixed thead end--> </body> </html>

    将其设置为居右16px;这个宽度基本上和滚动条的宽度一致,也可以自由设定 还需要js控制其宽度,若没有滚动条则居右0px;需要js检测表中div是否有滚动条 js代码:

    $(function(){ <!--获取屏幕高度--> var y = window.screen.availHeight; <!--设置滚动div高度--> document.getElementsByClassName("scrolltable")[0].style.height=y-400+"px"; <!--获取表体行数--> var rows = document.getElementById("searchresult").rows.length; <!--获取表头行数--> var rows2 = document.getElementById("table1").rows.length; <!--如果结果存在的话--> if(rows > 0){ <!--获取结果集的列数--> var cells = document.getElementById("searchresult").rows[0].cells.length; for(var i=0;i<cells;i++){ <!--循环遍历,将表体每列宽度赋值为表头对应列的宽度--> document.getElementById("table1").rows[0].cells[i].width =document.getElementById("searchresult").rows[0].cells[i].offsetWidth; } <!--获取滚动区--> var obj = document.getElementById("datatable"); if(obj.scrollHeight > obj.clientHeight || obj.offsetHeight > obj.clientHeight){ }else{ <!--如果没有滚动条,则居右0px--> document.getElementById("fixthead").style.marginRight = "0px"; } } })

    若有不明,可以留言,原创,若转载请标明出处!谢谢!

    转载请注明原文地址: https://ju.6miu.com/read-8700.html

    最新回复(0)