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);
相关推荐
子兮曰16 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖16 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神16 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛18 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华18 小时前
echarts使用案例
android·javascript·echarts
北原_春希18 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS18 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊18 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜18 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive18 小时前
Vue3使用ECharts
前端·javascript·echarts