1

// 计算字符串所占用的宽度的方法
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;
};


2 声望2 粉丝