背景:
使用layuitable显示列表数据时html表格高度,有时cell的内容有多行。 这时候就需要将cell的高度设置为自适应。 在这些情况下html表格高度,如果表格的各个列是固定的(固定的),就会导致固定列的样式乱序,排序时样式也会乱序,需要特殊处理。
解决方案:
渲染表格数据时,根据单元格的内容高度重新估计并设置表格每一行的高度。 窃听表格的排序风暴,根据排序风暴中单元格的内容高度重新估计并设置表格每一行的高度。
乱式疗效:
款式正常疗效:
源代码:
layui table单元格高度自适应造成固定的表格列样式错乱
body {
padding: 20px;
}
/* 设置表格单元格内容自适应 */
.layui-table-cell {
height: auto!important;
}
layui.use(['table'], function () {
var table = layui.table, $ = layui.$;
// 服务端返回的原始数据(数据中的tagName字段内容有多行)
var productListData = {
"status": 0,
"message": "ok",
"total": 5,
"data": {
"list": [
{
"id": 1,
"productName": "短袖",
"tagName": "服装
夏季上衣",
"createTime": "2022-07-01 12:30:12",
"updateTime": "2022-07-01 12:30:12"
},
{
"id": 2,
"productName": "长袖",
"tagName": "服装",
"createTime": "2022-07-01 12:30:12",
"updateTime": "2022-07-01 12:30:12"
},
{
"id": 3,
"productName": "长裤",
"tagName": "男装",
"createTime": "2022-07-01 12:30:12",
"updateTime": "2022-07-01 12:30:12"
},
{
"id": 4,
"productName": "衬衣",
"tagName": "男装
夏装",
"createTime": "2022-07-01 12:30:12",
"updateTime": "2022-07-01 12:30:12"
},
{
"id": 5,
"productName": "电脑",
"tagName": "电子产品
办公",
"createTime": "2022-07-01 12:30:12",
"updateTime": "2022-07-01 12:30:12"
}
]
}
};
// 由于是演示程序, 这里直接取出商品数据用于表格渲染
var listData = productListData.data.list;
// 表格渲染
window.ins1 = table.render({
elem: '#demo',
// url: 'http://localhost/getProductList', // 这里是服务端接口的地址
data: listData, // 直接赋值静态数据。真实数据需要通过请求服务端接口获取, 由于是演示程序, 这里直接使用data字段设置静态数据
limit: 20,
toolbar: '#toolbarDemo',
cols: [[
{ field: 'id', title: 'ID', fixed: "left", sort: true }, // ID列固定左侧
{ field: 'productName', title: '商品名称' },
{ field: 'tagName', title: '商品标签' },
{ field: 'createTime', title: '创建时间', sort: true },
{ field: 'updateTime', title: '最近一次更新时间', sort: true }
]],
parseData: function (res) {
return {
"status": res.status,
"msg": res.message,
"count": res.total,
"data": res.data.list
};
},
done: function () {
// layui表格单元格设置高度自适应后, 设置为fixed的表格列的高度无法自适应的处理
$(".layui-table-main tr").each(function(index, val) {
$($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
});
},
error: function (res, msg) {
console.log(res, msg)
}
});
table.on('sort(demo)', function(obj){ // sort 是工具条事件名, demo是table原始容器的属性
// 如果你的表格列表里有设置排序sort, 需要添加一个sort监听事件, 根据单元格内容的高度重新计算表格的行高
$(".layui-table-main tr").each(function(index, val) {
$($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
});
});
});