【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'
});
相关推荐
zithern_juejin4 小时前
new 运算符
javascript
前端毕业班4 小时前
uniapp web 灵活控制 style scoped
前端·javascript·vue.js
张元清5 小时前
在 React 里写动画又不跟渲染周期较劲:useRafFn、useRafState、useFps、useDevicePixelRatio、useUpdate
前端·javascript·面试
光影少年6 小时前
Redux 核心流程:Action、Reducer、Store、Dispatch
前端·react.js·掘金·金石计划
甜味弥漫6 小时前
JavaScript 底层逻辑:从内存视角看原型与原型链
前端·javascript
咪饭只吃一小碗6 小时前
JS this 身世大揭秘:它到底该听谁的?
前端·javascript
周淳APP7 小时前
【前端八股第一弹】
开发语言·前端·javascript·react.js
SmartBoyW7 小时前
撕掉前端黑魔法外衣:用 C++/Java 指针思维硬核拆解 JS 原型链
前端·javascript
不好听6137 小时前
数组去重的六种解法
javascript
ftpeak7 小时前
WebMCP Nexus:让 React 应用成为 AI Agent 可驱动的工具
前端·人工智能·react.js