【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'
});
相关推荐
一 乐18 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
xkxnq20 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
Van_Moonlight20 小时前
RN for OpenHarmony 实战 TodoList 项目:空状态占位图
javascript·开源·harmonyos
xkxnq20 小时前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
BBBBBAAAAAi1 天前
Claude Code安装记录
开发语言·前端·javascript
源码获取_wx:Fegn08951 天前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
Jing_Rainbow1 天前
【 前端三剑客-37 /Lesson61(2025-12-09)】JavaScript 内存机制与执行原理详解🧠
前端·javascript·程序员
UIUV1 天前
模块化CSS学习笔记:从作用域问题到实战解决方案
前端·javascript·react.js
Kakarotto1 天前
使用ThreeJS绘制东方明珠塔模型
前端·javascript·vue.js
donecoding1 天前
TypeScript `satisfies` 的核心价值:两个例子讲清楚
前端·javascript