layui table表格组件 toolbar操作栏自适应宽度
最近在使用Layui时发现table数据表格组件的toolbar操作栏不支持自适应宽度功能,于是上网查询了一些资料,发现相关文章很少,有几篇的写法是根据列ID来进行操作的,兼容性太低,于是决定自己实现。
效果
我们先看一下table组件的默认效果:
可以看到在按钮没有全部显示的情况下,右侧预留了很多空白位置,非常不美观。
再看一下我们实现自适应宽度后的效果:
可以看到,优化后列宽为本页数据需要使用的最大宽度,在某些情况下可省去很多位置。
好,效果看完了,我们接下来看下如何实现。
实现
首先我们的toolbar操作栏需要设置一个默认的宽度(width参数),需要大于你所有按钮的宽度总和。
注意需要使用unresize: true 来禁止用户通过拖拽更改列宽
代码如下:
{fixed: 'right', title: '操作', toolbar: '#actionBar', unresize: true, width: 260}
然后利用table组件的done函数来执行我们的自适应宽度逻辑:
代码如下:
done: function (res, curr, count) {
let maxWidth = 0;
let fixedRight = $(".layui-table-fixed-r");
//移除thead中原先的宽度样式
fixedRight
.children(".layui-table-header")
.children("table")
.children("thead")
.children("tr")
.each(function () {
$(this).children("th").children("div").removeClass();
$(this).children("th").children("div").addClass("layui-table-cell");
});
//移除tbody中原先的宽度样式,并计算出最后所需宽度
fixedRight
.children(".layui-table-body")
.children("table")
.children("tbody")
.children("tr")
.each(function () {
$(this).children("td").children("div").removeClass();
$(this).children("td").children("div").addClass("layui-table-cell");
maxWidth = $(this).width() - 30;
});
//修改thead中该列各单元格的宽度
fixedRight
.children(".layui-table-header")
.children("table")
.children("thead")
.children("tr")
.each(function () {
$(this).children("th").children("div").width(maxWidth);
});
//修改tbody中该列各单元格的宽度
fixedRight
.children(".layui-table-body")
.children("table")
.children("tbody")
.children("tr")
.each(function () {
$(this).children("td").children("div").width(maxWidth);
});
//由于layui的table组件中 浮动并不是单个单元格真浮动,而是实际上是新加了一个浮动对象覆盖在原先的单元格上,所以如果不写如下代码,会造成被覆盖的那一层单元格没有被完全覆盖的bug
$(".layui-table-box .layui-table-header")
.children("table")
.children("thead")
.children("tr")
.each(function () {
$(this).children("th:last").children("div").width(maxWidth);
});
$(".layui-table-box .layui-table-main")
.children("table")
.children("tbody")
.children("tr")
.each(function () {
$(this).children("td:last").children("div").width(maxWidth);
});
}
复制上述代码至你的项目中,基本不需要任何改动即可实现操作栏自适应宽度的效果。
备注
maxWidth = $(this).width() - 30;
其中这句代码中的 -30 是我测试后最好的一个修正值,当然,你的使用环境可能跟我的有所不同,如果需要进行一些修正,修改此值即可。
如果有更好的实现方式或该方法有任何的问题欢迎评论留言。
后记
在不同的使用环境中可能会出现一些奇怪的问题,后来的小伙伴可以查看评论区提供的解决方法。
1. 影响左边固定列的数据展示,将
$(".layui-table-box .layui-table-header")
替换为
$(".layui-table-box>.layui-table-header")