文章目录
代码实现
函数封装:
ts
export function getStringWidthDOM(
str: string,
{
fontSize = '16px',
fontFamily = 'Segoe UI Emoji, Segoe UI Symbol',
fontWeight = 'normal',
fontStyle = 'normal',
}: { fontSize?: string; fontFamily?: string; fontWeight?: string | number; fontStyle?: string },
): number {
const span = document.createElement('span');
span.style.cssText = `
position: absolute;
visibility: hidden;
white-space: nowrap;
font-size: ${fontSize};
font-family: ${fontFamily};
font-weight: ${fontWeight};
font-style: ${fontStyle};
`;
span.textContent = str;
document.body.appendChild(span);
const width = span.offsetWidth;
document.body.removeChild(span);
return width;
}
使用案例:
ts
const width: number = getStringWidthDOM('Hello, TS!', {
fontSize: '14px',
fontWeight: 'bold'
});