【JS】计算任意字符串的像素宽度(px)
文章目录
- 代码实现
代码实现
函数封装:
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;
}
使用案例:
const width: number = getStringWidthDOM('Hello, TS!', {fontSize: '14px',fontWeight: 'bold'
});