JavaScript计算字符串文本的宽度
在使用echarts时,经常需要获取字符串的宽度与边缘进行对比,以下是通过js来获取任意字符串宽度的方法:
const getTextWidth = (text: string) => { // 创建临时元素 const _span = document.createElement('span'); // 放入文本 _span.innerText = text; // 设置文字大小 _span.style.fontSize = '12px'; // span元素转块级并隐藏 _span.style.position = 'absolute'; _span.style.visibility = 'hidden'; // span放入body中 document.body.appendChild(_span); // 获取span的宽度 const width = _span.offsetWidth; // 从body中删除该span document.body.removeChild(_span); // 返回span宽度 return width; };
复制