【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'
});
相关推荐
ObjectX前端实验室12 分钟前
【图形编辑器架构】🧠 Figma 风格智能选择工具实现原理【猜测】
前端·react.js
技术钱33 分钟前
react+andDesign+vite+ts从零搭建后台管理系统(三)-Layout布局
javascript·react.js·ecmascript
郝开1 小时前
7. React组件基础样式控制:行内样式,class类名控制
react.js
DoraBigHead2 小时前
🧭 React 理念:让时间屈服于 UI —— 从同步到可中断的演化之路
前端·javascript·面试
千码君20162 小时前
React Native:发现默认参数children【特殊的prop】
javascript·react native·ecmascript·react·组件树
Never_Satisfied3 小时前
在JavaScript / HTML中,line-height是一个CSS属性
javascript·css·html
用户916357440954 小时前
LeetCode热题100——15.三数之和
javascript·算法
skykun4 小时前
都2026年了还在说闭包吗?
javascript
饮水机战神4 小时前
小程序被下架后,我连夜加了个 "安全接口"
前端·javascript
柯南二号4 小时前
【大前端】 TypeScript vs JavaScript:全面对比与实践指南
前端·javascript·typescript