本文將介紹如何使用Layui實(shí)現(xiàn)復(fù)雜表頭,包含多行多列表頭和合并單元格等功能。
一、多行多列表頭
在實(shí)際項(xiàng)目中,表格的表頭通常不僅包含一行標(biāo)題,還會(huì)有更復(fù)雜的表頭需求,如下圖所示:
標(biāo)題1
標(biāo)題2
標(biāo)題3
子標(biāo)題21
子標(biāo)題22
子標(biāo)題31
子標(biāo)題32
內(nèi)容1
內(nèi)容2-1
內(nèi)容2-2
內(nèi)容3-1
內(nèi)容3-2
通過(guò)rowspan
和colspan
屬性來(lái)實(shí)現(xiàn)多行列合并,rowspan
合并行,colspan
合并列,示例代碼如下:
th[ rowspan ]{
vertical-align: middle !important;
text-align: center !important;
}
th[ colspan ]{
vertical-align: middle !important;
text-align: center !important;
}
二、合并單元格
在實(shí)際項(xiàng)目中,表格的內(nèi)容需要合并單元格,如下圖所示:
標(biāo)題1
標(biāo)題2
標(biāo)題3
內(nèi)容1
內(nèi)容2-1
內(nèi)容3-1
內(nèi)容2-2
通過(guò)rowspan
和colspan
屬性來(lái)實(shí)現(xiàn)單元格合并,示例代碼如下:
td[ rowspan ]{
vertical-align: middle !important;
text-align: center !important;
}
td[ colspan ]{
vertical-align: middle !important;
text-align: center !important;
}
三、表格列寬自適應(yīng)
在實(shí)際項(xiàng)目中,表格的列寬不一定相等,需要設(shè)置列寬自適應(yīng)表格寬度,如下圖所示:
標(biāo)題1
標(biāo)題2
標(biāo)題3
內(nèi)容1
內(nèi)容2-1
內(nèi)容3-1
內(nèi)容1
內(nèi)容2-2
內(nèi)容3-2
通過(guò)設(shè)置table-layout: fixed;
屬性,將表格的布局模式設(shè)置為固定,示例代碼如下:
.layui-table td, .layui-table th{
padding: 10px 8px;
text-align: center;
font-size: 14px;
line-height: 22px;
height: auto;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.layui-table td{
border-width: 0;
border-bottom: 1px solid #e2e2e2;
}
.layui-table th{
color: #666;
background-color: #f2f2f2;
font-weight: 400;
border-width: 0;
border-bottom: 1px solid #e2e2e2;
}
table {
border-collapse: collapse;
table-layout: fixed;
border-radius: 4px;
overflow: hidden;
}
四、單元格內(nèi)文字溢出處理
在實(shí)際項(xiàng)目中,表格的單元格內(nèi)文字可能會(huì)過(guò)長(zhǎng),需要設(shè)置文字溢出顯示省略號(hào),如下圖所示:
.layui-table td{
padding: 10px 8px;
text-align: center;
font-size: 14px;
line-height: 22px;
height: auto;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
五、分頁(yè)與搜索
在實(shí)際項(xiàng)目中,表格的數(shù)據(jù)可能會(huì)很多,需要設(shè)置分頁(yè)和搜索功能來(lái)提高用戶體驗(yàn)和數(shù)據(jù)查詢(xún)效率,如下圖所示:
layui.use('table', function(){
var table = layui.table;
//執(zhí)行渲染
table.render({
elem: '#demo'
,url: '/demo/table/user/' //數(shù)據(jù)接口
,page: true //開(kāi)啟分頁(yè)
,loading:true //開(kāi)啟loading
,where: 'where條件'
,cols: [[ //表頭
{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
,{field: 'username', title: '用戶名', width:120}
,{field: 'sex', title: '性別', width:80, sort: true}
,{field: 'city', title: '城市', width:100}
,{field: 'sign', title: '簽名', width: 200,templet: function(d){ return d.sign }}
,{field: 'experience', title: '積分', width: 80, sort: true}
,{field: 'score', title: '評(píng)分', width: 80, sort: true}
,{field: 'classify', title: '職業(yè)', width: 100}
,{field: 'wealth', title: '財(cái)富', width: 135, sort: true,templet: function(d){
return '¥' + d.wealth;
}}
]]
});
});
使用Layui的table
組件,通過(guò)page: true
屬性開(kāi)啟分頁(yè),loading:true
屬性開(kāi)啟loading,通過(guò)where
屬性傳遞where條件,示例代碼如上。