layui 2.9.16 版本,根据字段字数最大数,表格自适应字段宽度

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);
相关推荐
kyriewen1 分钟前
Claude Code后天起默认Auto模式了——我第一时间改了这6个设置
前端·ai编程·claude
码哥DFS42 分钟前
构造函数、实例对象、对象原型 ----三者关系
开发语言·javascript·原型模式
风骏时光牛马42 分钟前
智能赋能型AI办公一体化系统架构
前端
满栀5851 小时前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
土豆~1 小时前
文件名没后缀就打不开:前端文件预览的内容嗅探改造
前端·状态模式
Euato_Key2 小时前
全栈视野学习Cookie——理解 Cookie 的本质
前端
前端开发呀2 小时前
我的 AI 终端配置清单
前端
敲代码的玉米C2 小时前
测试一直在写你的真实数据根
前端·人工智能·架构
jjw_zyfx3 小时前
css vue vite实现闪烁的呼吸效果
javascript·css·vue.js