【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'
});
相关推荐
梦想CAD控件25 分钟前
网页端CAD的图形选择、编辑与夹点操作教程
前端·javascript·node.js
月月大王的3D日记40 分钟前
Three.js 入门系列(8):六种光源全解析 —— 关灯了,开光!
前端·javascript
自然 醒1 小时前
v-tooltip自定义指令封装
前端·javascript·vue.js
mONESY2 小时前
🎨 从零搭建 React + TypeScript + Vite 项目:以 Color Picker 为例,聊聊前端工程化的 model/api 分层架构
react.js
其美杰布-富贵-李3 小时前
第 10 篇:灯光与阴影
javascript·three.js
小高0075 小时前
🔥🔥🔥TypeScript 7 正式版来了:别只看 10 倍速度,这 4 个迁移坑更值得注意
前端·javascript·面试
di24k24k6 小时前
多个 el-form 共用同一 ref 导致表单校验部分失效
前端·javascript·vue.js·elementui
JKooll6 小时前
WPS 表格 DISPIMG 函数实战:用 JavaScript 将图片真正嵌入单元格
javascript·wps
晴天167 小时前
Rust 快速入门 (从 JavaScript 开发者视角)-Day09
开发语言·javascript·rust
其美杰布-富贵-李7 小时前
第 6 篇:相机与 OrbitControls
前端·javascript·three.js