共计 396 个字符,预计需要花费 1 分钟才能阅读完成。
JavaScript 计算字符串文本的宽度
在使用 echarts 时,经常需要获取字符串的宽度与边缘进行对比,以下是通过 js 来获取任意字符串宽度的方法:
const getTextWidth = (text: string) => {
const _span = document.createElement('span');
_span.innerText = text;
_span.style.fontSize = '12px';
_span.style.position = 'absolute';
_span.style.visibility = 'hidden';
document.body.appendChild(_span);
const width = _span.offsetWidth;
document.body.removeChild(_span);
return width;
};
原文地址: JavaScript 计算字符串文本的宽度
正文完