计算字符串所占的宽度像素的方法
文章目录
// 计算字符串所占用的宽度的方法
const getTextWidth = (text: string, fontSize: number, fontWeight: string) => {
// 创建临时元素
const ele: HTMLElement = document.createElement('div');
ele.style.position = 'absolute';
ele.style.whiteSpace = 'nowrap';
ele.style.fontSize = fontSize + 'px';
ele.style.fontWeight = fontWeight;
ele.innerText = text;
document.body.append(ele);
// 获取span的宽度
const width: number = ele.getBoundingClientRect().width;
// 从body中删除该span
document.body.removeChild(ele);
console.log(text + '_' + width);
// 返回span宽度
return width;
};
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论