產品要求是一個頁面要顯示幾千條數據,表格的表頭固定,而內容在超出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>