layui table表格組件 toolbar操作欄自適應寬度

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 是我測試後最好的一個修正值,當然,你的使用環境可能跟我的有所不同,如果需要進行一些修正,修改此值即可。

代碼量還是挺多的,如果有更好的實現方式歡迎評論留言。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章