【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'
});
相关推荐
Amumu1213820 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
Sgf22720 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
Cobyte1 天前
1.基于依赖追踪和触发的响应式系统的本质
前端·javascript·vue.js
老神在在0011 天前
【Selenium 自动化精讲】浏览器弹窗与登录界面的本质区别 & 实操指南
javascript·学习·selenium·测试工具·自动化
前端小咸鱼一条1 天前
16.迭代器 和 生成器
开发语言·前端·javascript
前端小阳1 天前
JavaScript原型链
javascript
早點睡3901 天前
ReactNative项目OpenHarmony三方库集成实战:react-native-collapsible
javascript·react native·react.js
前端Hardy1 天前
别再手写代码了!2026 前端 5 个 AI 杀招,直接解放 80% 重复劳动(附工具+步骤)
前端·javascript·面试
SuperEugene1 天前
Element Plus/VXE-Table UI 组件库规范:统一用法实战,避开样式冲突与维护混乱|工程化与协作规范篇
前端·javascript·vue.js·ui·前端框架·element plus·vxetable
前端Hardy1 天前
前端工程师必备的 10 个 AI 万能提示词(Prompt),复制直接用,效率再翻倍!
前端·javascript·面试