【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'
});
相关推荐
vx-程序开发1 小时前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
用户938515635072 小时前
React 受控/非受控组件与 React.memo 性能优化——从本质到实战
前端·javascript·react.js
其美杰布-富贵-李3 小时前
第 8 篇:Three.js 材质系统
javascript·three.js·js
To_OC3 小时前
LC 3 无重复字符的最长子串:从入门滑动窗口到优化写法,再也不怕面试官追问
javascript·算法·leetcode
半个落月3 小时前
从零梳理 React Router:路由、懒加载、嵌套页面与登录鉴权
前端·react.js
默_笙4 小时前
🚩 React + TypeScript 的 Props 通信,我从"把事件对象传给父组件"进化到了"只传值"
前端·javascript
渣波4 小时前
赋予 React “多线程”:Hooks + Web Worker 并发计算架构深度解析
前端·javascript
光影少年4 小时前
Codex 斜杠指令体系与业务场景调度实战
前端·react.js·reactivex
Darling噜啦啦6 小时前
别再逐层传 Props 了!useContext + 自定义 Hook 彻底搞定 React 跨层通信
react.js
先吃饱再说6 小时前
层层传递太“痛”了:useContext 给 React 组件装了个“无线遥控器”
前端·react.js·前端框架