/** * 使用span标签包裹内容,计算文本宽度 * @param text 要计算的文本 * @param customCssText 自定义CSS样式 * @returns 文本的像素宽度 */ // 更简单的版本:直接拼接 CSS 文本(性能更好) export function getTextWidth(text: string, customCssText: string = ""): number { if (!text) return 0; const span = document.createElement("span"); span.textContent = text; // 构建最终的 CSS 文本 const defaultCssText = ` position: absolute; visibility: hidden; white-space: nowrap; font-family: inherit; font-size: inherit; font-weight: inherit; letter-spacing: inherit; padding: 0; margin: 0; border: 0; box-sizing: border-box; `; // 合并样式:自定义样式放在后面,以便覆盖默认样式 span.style.cssText = defaultCssText + (customCssText ? customCssText : ""); document.body.appendChild(span); const width = span.offsetWidth; document.body.removeChild(span); return width; } /** * 遍历数据获取最大宽度 * @param data 需要计算的数据数组 * @param minWidth 最小宽度,默认60px * @param customCssText 自定义CSS样式 * @returns 最大宽度 */ export function getMaxLength( data: (string | number | null | undefined)[], minWidth: number = 60, customCssText: string = "" ): number { if (!data || data.length === 0) return minWidth; const maxWidth = data.reduce((acc: number, item) => { if (item !== null && item !== undefined) { const text = String(item); const calcLen = getTextWidth(text, customCssText); if (acc < calcLen) { acc = calcLen; } } return acc; }, 0); return Math.max(maxWidth, minWidth); }