【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'
});
相关推荐
GISer_Jing1 小时前
Three.JS渲染架构解读
java·javascript·架构
时寒的笔记2 小时前
day13~14核心案例某采招网
开发语言·javascript·ecmascript
智商不够_熬夜来凑2 小时前
【Picker】单选多选
前端·javascript·vue.js
米饭不加菜3 小时前
Typora 原生流程图语法完全指南(Flowchart.js)
前端·javascript·流程图
scan7243 小时前
langgraphy条件边
前端·javascript·html
用户938515635073 小时前
《JS 对象知识地图:10 个小节,从字面量到原型链全覆盖》
javascript
YAwu114 小时前
JavaScript this 底层机制剖析
前端·javascript
tedcloud1234 小时前
wifi-densepose部署教程:构建无线人体感知系统
服务器·javascript·网络·typescript·ocr
用户852495071844 小时前
帮你搞清楚对付js里对象的小妙招^_^
javascript