【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'
});
相关推荐
丷丩1 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
xiaohua0708day2 小时前
Lodash库
前端·javascript·vue.js
突然好热2 小时前
TS 调试技巧
前端·javascript·typescript
h64648564h2 小时前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
丷丩3 小时前
MapLibre GL JS第8课:禁用滚动缩放
javascript·mapbox·maplibre gl js
kyriewen5 小时前
面试8家前端岗位后,我发现了一个残酷的事实:AI不是加分项,是门槛
前端·javascript·面试
GISer_Jing7 小时前
前端沙箱开源项目推荐(React/Next/Vue优先)
前端·react.js·开源
MageGojo8 小时前
做节日活动页时,如何用 API 快速生成对联内容
javascript·python·节日·对联生成
向上的车轮8 小时前
Next.js 入门指南:从零到一构建全栈应用
开发语言·javascript·ecmascript
freeinlife'8 小时前
精准秒表计时器实现---基于js
开发语言·前端·javascript