pp-web/scripts/flexColumnWidth.js

82 lines
3.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 根据内容设置列表宽度
function flexColumnWidth(str, arr1, fontNum = 4, flag = 'max') {
// str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
// fontNum为该列标题字体个数(默认为4);
// flag为可选值可不传该参数,传参时可选'max'或'equal',默认为'max'
// flag为'max'则设置列宽适配该列中宽度最大的内容,flag为'equal'则设置列宽适配该列中第一行内容的宽度。
str = str + '';
// 验证输入参数
if (!arr1 || !arr1.length) return fontNum * 14 + 5;
if (!str || !str.length) return fontNum * 14 + 5;
// 计算单个内容的宽度
const calculateContentWidth = (content) => {
let width = 0;
const contentStr = content + '';
if (contentStr.includes('长') && contentStr.includes('宽') && contentStr.includes('高')) {
width += 23;
}
for (const char of contentStr) {
if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9')) {
// 英文字符分配8个单位宽度
width += 8;
} else if ((char >= '\u4e00' && char <= '\u9fa5') || (char >= '\uff00' && char <= '\uffef') ||
char === '×' || char === 'Φ' || char === '' || char === '' || char === '' ||
char === '。' || char === '' || char === '' || char === '' || char === '' || char === '、' ||
char === '“' || char === '”' || char === '' || char === '' || char === '《' || char === '》') {
// 中文字符、全角标点及特定符号分配13个单位宽度
width += 13;
} else if (char === ' ' || char === ',' || char === '.') {
// 空格分配4个单位宽度
width += 4;
} else {
// 其他字符分配4个单位宽度
width += 8;
}
}
return width;
};
let targetWidth = 0;
if (flag === 'equal') {
// 获取该列中第一个不为空的数据并计算其宽度
for (let i = 0; i < arr1.length; i++) {
if (arr1[i][str] !== null && arr1[i][str] !== undefined) {
targetWidth = calculateContentWidth(arr1[i][str]);
break;
}
}
} else {
// 计算每一项的宽度,找出最大宽度
let maxWidth = 0;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i][str] === null) return;
const currentWidth = calculateContentWidth(arr1[i][str]);
if (currentWidth > maxWidth) {
maxWidth = currentWidth;
}
if (currentWidth > maxWidth) {
maxWidth = currentWidth;
}
}
targetWidth = maxWidth;
}
// 计算标题最小宽度
const titleMinWidth = fontNum * 14;
// 比较内容宽度和标题最小宽度,取较大值
const flexWidth = Math.max(targetWidth, titleMinWidth);
// 返回最终宽度加上额外的5px
return flexWidth + 5;
}
window.flexColumnWidth = flexColumnWidth