计算dom元素
这里有一个痛点,当你做国际化的时候,不知道生成出来的文本的长度,容易有样式方面的问题,比如超出长度或者等等。
- 如果想要计算这个字符串长度,是不是还得看样式里的fontsize 然后计算中文字符有多少个,英文字符有多少个,然后大概算出长度,但这样的长度一定是有误差的,而且文字可能不止中文和英文两种,所以这个思路就被pass了
- 元素是生成在html中的,这个时候我们为什么不传入相同的样式,让它生成在html文档中,然后通过
dom.clientWidth
来获取呢,这个是一个好方法,所以我们是用这个方法尝试一下
type IHTMLStyleInJs = {
fontSize: number;
fontStyle: string;
fontWeight: string;
lineHeight: number;
};
const getHTMLTextStyleWidth = (str = '', style: IHTMLStyleInJs): number => {
const dom = document.createElement('div');
dom.style.display = 'inline-block';
dom.style.fontSize = `${style.fontSize || 12}px`;
dom.style.fontStyle = style.fontStyle || 'normal';
dom.style.fontWeight = style.fontWeight || 'normal';
dom.style.lineHeight = `${style.lineHeight || 20}px`;
dom.textContent = str;
document.body.appendChild(dom);
const width = dom.clientWidth;
document.body.removeChild(dom);
return width;
};
export default getHTMLTextStyleWidth;
果然通过和这个方法解决了上述问题!!!
有问题可以common