【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'
});
相关推荐
用户9385156350722 分钟前
从零打造你的第一个智能体(Agent):*手写一个能自主建项目的Mini Cursor (三)
javascript·人工智能·后端
aichitang202440 分钟前
Claude fable 5与GPT5.5模型能力实测
javascript·css·人工智能·ai·html·html5
多加点辣也没关系41 分钟前
JavaScript|第6章:流程控制语句
开发语言·前端·javascript
csj5041 分钟前
前端基础之《React(11)—state声明式》
前端·react.js
用户9385156350744 分钟前
手写迷你 Cursor 终端:深入 Node.js child_process 的 spawn 核心实现
javascript·后端
Csvn1 小时前
AbortController 不止能取消 Fetch!3 个你不知道的隐藏用法
前端·javascript
大流星1 小时前
LangChainJS之Runnable(三)
javascript·langchain
张元清1 小时前
React useLocalStorage Hook:SSR 安全的持久化状态(2026)
javascript·react.js
甜味弥漫2 小时前
React Router:从单页应用到前端路由
javascript·node.js
lkshop2 小时前
Next.js 网站 SEO 优化:从 SSR、Sitemap 到结构化数据
开发语言·javascript·ecmascript