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);
相关推荐
半个落月4 小时前
LangSmith 全链路观测(下):用 Dataset 与 LLM Judge 量化评估 RA
javascript·langchain
半个落月5 小时前
LangSmith 全链路观测(上):用 LangGraph 与 Milvus 构建可追踪的 RAG 客服
javascript·langchain
Java后端的Ai之路6 小时前
06-React-Props
前端·react.js·前端框架
半个落月6 小时前
LangChain.js Agent 中间件实战:生命周期、动态工具与文件权限
javascript·langchain
Flynt6 小时前
开源"间谍卫星"说数据全是真的,我把它的免key数据源挨个试了一遍
前端·开源·数据可视化
Csvn7 小时前
渲染管线
前端
程序员大阳7 小时前
副队长CSS教程(33)–圆角与透明
前端·css·透明·圆角
志尊宝7 小时前
Vue3 零基础每日笔记(082):文件上传实战——el-upload 校验、自定义上传、头像预览
前端·javascript·vue.js·笔记·#javascript·#vue.js
鬼手点金7 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
柳杉7 小时前
借助 Codex 和可视化工作流,从调研到完整实现,3D 大屏竟然可以这么简单
前端·ai编程·数据可视化