【JS】计算任意字符串的像素宽度(px)

文章目录

代码实现

函数封装:

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'
});
相关推荐
不好听61312 分钟前
JavaScript 的 this 到底指向谁?
javascript·面试
触底反弹15 分钟前
🔥 2026 年爆火的 Harness Engineering 到底是什么?从原理到实战一文讲透
javascript·人工智能·程序员
mONESY15 分钟前
一文搞定JavaScript不同场景中 this 的指向问题
javascript
用户2986985301425 分钟前
在 React 中使用 JavaScript 合并 Excel 文件
前端·javascript·react.js
大流星28 分钟前
LangChainJs之基础模型(一)
javascript·langchain
橘子星31 分钟前
JavaScript this 指向全解实战指南
前端·javascript
weedsfly33 分钟前
JS垃圾回收:从原理到项目实战,彻底根治内存泄漏
前端·javascript·面试
万少12 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童15 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript