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);
相关推荐
掘金安东尼5 分钟前
纯 CSS 实现弹性文字效果
前端·css
牛奶38 分钟前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶44 分钟前
Vue 底层原理 & 新特性
前端·vue.js·面试
anOnion1 小时前
构建无障碍组件之Radio group pattern
前端·html·交互设计
pe7er1 小时前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
SoaringHeart2 小时前
Flutter调试组件:打印任意组件尺寸位置信息 NRenderBox
前端·flutter
晚风予星3 小时前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
sunny_3 小时前
⚡️ vite-plugin-oxc:从 Babel 到 Oxc,我为 Vite 写了一个高性能编译插件
前端·webpack·架构
GIS之路3 小时前
ArcPy 开发环境搭建
前端
林小帅4 小时前
【笔记】OpenClaw 架构浅析
前端·agent