1、封装一个公共方法在文件上
公共路径 "/assets/common/js/tableUtils.js"
代码如下:
bash
// tableUtils.js
function adjustTableFieldWidth(fieldName, cellClass, minWidth = 100) {
// 获取所有单元格内容
let maxLength = 0;
let cells = document.querySelectorAll(`.layui-table-body ${cellClass}`);
// 遍历所有单元格,找到最长的内容长度
cells.forEach(cell => {
let content = cell.textContent || cell.innerText;
let length = content.length;
if (length > maxLength) {
maxLength = length;
}
});
// 计算宽度
let width = maxLength * 14 + 30; // 每个字符宽度按指定值计算
width = Math.max(width, minWidth); // 确保最小宽度
console.log(`${fieldName} width:`, width);
// 设置表头宽度
let headerCell = document.querySelector(`.layui-table-header [data-field="${fieldName}"] .layui-table-cell`);
if (headerCell) {
headerCell.style.width = `${width}px`;
}
// 设置所有单元格宽度
cells.forEach(cell => {
cell.style.width = `${width}px`;
});
}
// 将方法挂载到 layui 对象上,以便在其他文件中通过 layui.tableUtils 调用
layui.define([], function(exports) {
exports('tableUtils', {
adjustTableFieldWidth: adjustTableFieldWidth
});
});
2、html引入
@layout("/common/_container_latest.html",{js:["/assets/purchase/order/purchase_list.js","/assets/common/js/dayJs.min.js","/assets/common/js/tableUtils.js"]}){
3、js引入
bash
layui.extend({
defHttp: '../utils/defHttp',
numberUtil: '../utils/numberUtil'
}).use(['table', 'admin', 'ax', 'func', 'laydate', 'defHttp', 'numberUtil'], function () {
var $ = layui.$;
var table = layui.table;
var tableUtils = layui.tableUtils;
// 对应文件调用
// 调整下单人字段宽度
tableUtils.adjustTableFieldWidth('createUserName', '.laytable-cell-1-0-7',100);