如何使用Javascript根据容器宽度渲染数组元素,溢出时显示省略号
JS实现数组文本自适应500px容器宽度显示方案
核心逻辑
通过测量文本实际渲染宽度判断是否超出容器容量,放不下的内容统一替换为...,不需要依赖字符数估算,适配不同字符宽度场景。
实现代码
1. 文本宽度测量工具函数(canvas方案,性能最优)
// 测量指定文本在10px字号下的实际渲染宽度 function measureTextWidth(text) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // 字体配置需和实际页面渲染的字体完全一致,避免宽度误差 ctx.font = '10px sans-serif'; return ctx.measureText(text).width; }
2. 数组处理逻辑
/** * 处理文本数组,适配指定容器宽度 * @param {Array} arr 待处理的文本数组 * @param {Number} containerWidth 容器宽度,默认500px * @returns {String} 格式化后的展示字符串 */ function formatArrayForContainer(arr, containerWidth = 500) { const result = []; let usedWidth = 0; // 提前计算省略号和分隔符的宽度 const ellipsisWidth = measureTextWidth('...'); const separatorWidth = measureTextWidth(', '); for (let i = 0; i < arr.length; i++) { const currentText = arr[i]; const currentTextWidth = measureTextWidth(currentText); const totalNeedWidth = usedWidth + currentTextWidth; // 剩余宽度足够放下当前文本 if (totalNeedWidth <= containerWidth) { result.push(currentText); usedWidth = totalNeedWidth; // 不是最后一个元素的话,要预留分隔符的宽度 if (i !== arr.length - 1) { if (usedWidth + separatorWidth > containerWidth) { // 分隔符都放不下,直接加省略号终止 result.push('...'); break; } usedWidth += separatorWidth; } } else { // 放不下当前文本,判断是否够放省略号 if (usedWidth + ellipsisWidth <= containerWidth) { result.push('...'); } break; } } return `[${result.join(', ')}]`; }
3. 使用示例
const demoArr = ['john', 'johnbbab', 'johnabraham']; // 容器无法容纳第二个元素时,输出为 [john, ...] console.log(formatArrayForContainer(demoArr));
兼容方案(兼容低版本浏览器)
如果需要兼容不支持canvas的老旧浏览器,可以用隐藏DOM的方式测量宽度,替换measureTextWidth函数即可:
function measureTextWidth(text) { const span = document.createElement('span'); span.style.cssText = ` font: 10px sans-serif; position: absolute; visibility: hidden; whiteSpace: nowrap; `; span.textContent = text; document.body.appendChild(span); const width = span.offsetWidth; document.body.removeChild(span); return width; }
注意事项
- 测量宽度时的字体配置必须和页面实际渲染的字体、字号完全一致,否则会出现计算误差
- 如果文本元素有额外的padding、margin间距,需要把对应宽度也加入总容量的计算逻辑
内容的提问来源于stack exchange,提问作者johnbbab
相关产品推荐
相关产品推荐

