在做私活的時候,有一個需求是要在頁面上實作多層表頭。一開始有點懵,不知道怎麼來實作,我回想起在JFTT的時候,曾用過Flex版的多層表頭,不過那離現在已經很久遠了,久遠到Flex已經被淘汰出局了。于是在網上折騰了好一會兒,終于找到一款用起來簡單,效果又很不錯的元件——Bootstrap-table。
Bootstrap-table還有很多強大的功能,但這篇文章我們把關注點隻放在多層表頭上,關注點确定後,這篇部落格就很簡單了,但我覺得還是很有必要推而廣之——因為之前在看董卿主持的《詩詞大會》,裡面有很多基礎的知識,竟然有很多人都答不上來,搞得我一度很“嚣張”,對老婆誇下海口說我也能過第一輪,但事實是我過不了——我也不會寫“碧玉妝成一樹高,萬條垂下綠絲縧(tao)”中的tao字。
是以,文章不在于其難度,而在于其意義——在月球上邁上一小步和在地球上邁上一小步差别就在于“這是個人邁出的一小步,但卻是人類邁出的一大步。”
#0.效果圖

<html>
<head>
<title>多層表頭</title>
<link href="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="stylesheet">
<style type="text/css">
.table td, .table th {
font-style: normal;
font-weight: normal;
text-align:center;
}
.bootstrap-table {
width: 100%;
}
</style>
</head>
<body>
<table data-toggle="table">
<thead>
<tr>
<th data-colspan="1">妻子</th>
<th data-colspan="2">車子</th>
<th data-colspan="3">房子</th>
<th data-rowspan="2">總價值</th>
</tr>
<tr>
<th>唯一</th>
<th>Mini</th>
<th>Smart</th>
<th>90平</th>
<th>149平</th>
<th>别墅</th>
</tr>
</thead>
<tbody>
<tr>
<td>∞</td>
<td>30萬</td>
<td>20萬</td>
<td>60萬</td>
<td>100萬</td>
<td>看着辦</td>
<td>∞∞</td>
</tr>
</tbody>
</table>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
</body>
</html>
#2.具體步驟
第一步,通過CDN引入jquery和bootstrap-table。
<link href="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
第二步,第一層表頭;
<tr>
<th data-colspan="1">妻子</th>
<th data-colspan="2">車子</th>
<th data-colspan="3">房子</th>
<th data-rowspan="2">總價值</th>
</tr>
通過data-colspan指定二級表頭橫向有多少個,縱向為1;
通過data-rowspan指定二級表頭縱向有多少個,橫向為1;
第三步,第二層表頭;
<th>唯一</th>
<th>Mini</th>
<th>Smart</th>
<th>90平</th>
<th>149平</th>
<th>别墅</th>
注意data-rowspan="2"對應的第二層表頭就不需要指定了。
第三步,啟用bootstrap-table。
<table data-toggle="table">
</table>
嗯,不需要解釋了。