Table表头与数据列对齐问题解决方案
产品要求是一个页面要显示几千条数据,表格的表头固定,而内容在超出table的高度后,还能自由滚动。
公司前端框架采用easyui,而用easyui展示几千条数据的话,耗时需要在几秒钟,所以我就自己写了一个table,展示如下。
大部分朋友如果遇到这种情况的话,那么首先会想到做两个table,表头一个,数据体一个。我的写法是只有一个table。
(需要注意的是最后一列一定不要设置宽度,如果设置的话整体会往右移动,会导致表头与数据对不齐的情况)。
如下代码是我写的一个demo,动态绑定数据。
代码如下:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style> table tbody { display: block; height: 500px; overflow-y: scroll; } table thead, tbody tr { display: table; width: 100%; table-layout: fixed; } table thead { width: calc( 100% - 1em ); background: #e9f5f7; } table { border-width: 1px 1px 1px 1px !important; border: 1px solid #ccc; } table tbody tr td { border-bottom: 1px solid #ccc; border-left: 1px solid #ccc; word-wrap:break-word; } table thead tr th { border-width: 1px 1px 1px 1px !important; border-left: 1px solid #ccc; } .even { background-color: white; } .odd { background-color: #f5f5f5; } </style> </head> <body> <table width="80%" style="table-layout:fixed" id="tableValue" border="0" cellspacing="1" cellpadding="0"> <thead> <tr> <th style="border-left: none">姓名</th> <th style="width: 20px">年龄</th> <th style="width: 200px">出生年月</th> <th style="width: 20px">手机号码</th> <th style="width: 20px">单位</th> <th>姓名</th> <th>年龄</th> <th>出生年月</th> <th>手机号码</th> <th>单位</th> <th>姓名</th> <th>年龄</th> <th>出生年月</th> <th>手机号码</th> <th>单位</th> <th>姓名</th> <th>年龄</th> <th>出生年月</th> </tr> </thead> <tbody></tbody> </table> </body> </html> <script src="@Rison.Utilities.Resource.referenceUri/scripts/jquery/jquery-1.8.2.js" type="text/javascript"></script> <script type="text/javascript"> //页面加载 $(function () { var html = ""; var url = '../ProductAutoPurchase/List1'; $.ajax({ type: 'POST', url: url, success: function (data) { for (var i = 0; i < data.rows.length; i++) { var row = data.rows[i]; var trColor; //table--隔行变色 if (i % 2 == 0) { trColor = "even"; } else { trColor = "odd"; } html += "<tr class='" + trColor + "'>"; html += '<td style="border-left: none ">' + row.ProductSkuId + '</td>'; html += '<td style="width: 20px">' + row.ProductSkuCode + '</td>'; html += '<td style="width: 200px">' + row.ProductSkuFullName + '</td>'; html += '<td style="width: 20px">' + row.ProductSkuCode + '</td>'; html += '<td style="width: 20px">' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '<td>' + row.ProductSkuCode + '</td>'; html += '</tr>'; } $("#tableValue").append(html); } }); }); </script>