bootstrap 表格表頭固定
阿新 • • 發佈:2019-02-07
效果
效果是在pc端和移動端能夠使表格的表頭固定,並且在頂部,支援縮放時佈局不亂。
核心技術
利用css的position:fixed
屬性來脫離文件流,達到表頭固定的效果。
程式碼
說明都在程式碼裡面,這裡就不多說了。
<html>
<head>
<title>使用者表</title>
<!-- jquery庫-->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<!-- 最新版本的 Bootstrap 核心 CSS 檔案 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- 可選的 Bootstrap 主題檔案(一般不用引入) -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<!-- 最新的 Bootstrap 核心 JavaScript 檔案 -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- 移動端1:1縮放達到縮放佈局不亂的效果 -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<style>
th{
text-align:center;
}
table{
text-align:center;
}
.fixedhead{
position: fixed;
background: white;
}
</style>
</head>
<body>
<div class="container-fluid">
<!-- 僅含表頭的表格,與下面的表格表頭必須一致,然後將此表的css設定為position:fixed,脫離文件流,達到表頭固定的效果-->
<table class="table table-bordered table-striped fixedhead" id="fixedhead">
<thead>
<tr>
<th>使用者名稱</th>
<th>密碼</th>
<th>狀態</th>
</tr>
</thead>
</table>
<!-- 含有資料的表格,實際上表頭的內容不會被顯示,因為會被上面的表覆蓋,但也不要刪除表頭,因為需要佔位,否則表中第一行資料無法看到。-->
<table class="table table-bordered table-striped" id="user_table" >
<thead>
<tr>
<th>使用者名稱</th>
<th>密碼</th>
<th>狀態</th>
</tr>
</thead>
<tbody id="user_table_tbody">
<script>
//固定表頭的寬度,自適應user_table的寬度
function autoWidth()
{
document.getElementById("fixedhead").style.width = document.getElementById("user_table").offsetWidth;
}
window.onresize = function () {
//當視窗重繪,重新適應寬度
autoWidth();
}
window.onload = function(){
//頁面載入完畢,表頭表的自適應寬度
autoWidth();
}
//批量生成表格資料
var tbody = document.getElementById("user_table_tbody");
var inner = "";
for (var i=0;i<100;i++) {
inner += "<tr>";
for (var j=0;j<3;j++) {
inner += "<td>" +i+j + "</td>";
}
inner += "</tr>"
}
tbody.innerHTML = inner;
</script>
</tbody>
</table>
</div>
</body>
</html>