【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'
});
相关推荐
弓.长.16 分钟前
React Native 鸿蒙跨平台开发:BottomSheet 底部面板详解
javascript·react native·react.js
摘星编程30 分钟前
React Native for OpenHarmony 实战:Permissions 权限管理详解
javascript·react native·react.js
闲蛋小超人笑嘻嘻1 小时前
Vue 插槽:从基础到进阶
前端·javascript·vue.js
摘星编程1 小时前
React Native for OpenHarmony 实战:SearchBar 搜索栏详解
javascript·react native·react.js
梦6503 小时前
Vue 单页面应用 (SPA) 与 多页面应用 (MPA) 对比
前端·javascript·vue.js
清铎3 小时前
大模型训练_week3_day15_Llama概念_《穷途末路》
前端·javascript·人工智能·深度学习·自然语言处理·easyui
岛泪4 小时前
把 el-cascader 的 options 平铺为一维数组(只要叶子节点)
前端·javascript·vue.js
摘星编程4 小时前
React Native for OpenHarmony 实战:SecureStorage 安全存储详解
安全·react native·react.js
lendsomething4 小时前
graalvm使用实战:在java中执行js脚本
java·开发语言·javascript·graalvm
冰暮流星5 小时前
javascript的switch语句介绍
java·前端·javascript