传入一个字符串或标签返回其所占的长度

传入一个字符串或标签返回其所占的长度

思路说明

  1. 使用隐藏的div元素来插入传入的HTML纯字符串,并测量其宽度。
  2. 使用style="white-space: nowrap;"来确保字符串不换行。
  3. 使用隐藏的div元素offsetWidth来取得宽度。取得之后,要记得移除插入的元素。
  4. 此外,该方法可能受到浏览器渲染引擎和字体渲染的影响,实际宽度可能略有差异。

代码说明

function getStringWidth(input, fontSize = '12px') {
  // 创建一个隐藏的 div 元素
  const hiddenDiv = document.createElement('div');
  hiddenDiv.style.visibility = 'hidden';
  hiddenDiv.style.position = 'absolute';
  hiddenDiv.style.whiteSpace = 'nowrap';

  // 如果传入的是 HTML,则将其作为 innerHTML 插入 div
  if (/<[^>]+>/g.test(input)) {
    hiddenDiv.innerHTML = input;
  } else {
    // 如果传入的是纯字符串,则直接插入 div
    hiddenDiv.textContent = input;
  }

  // 设置字号
  hiddenDiv.style.fontSize = fontSize;

  // 将 div 插入到文档中
  document.body.appendChild(hiddenDiv);

  // 获取 div 的宽度
  const width = hiddenDiv.offsetWidth;

  // 从文档中移除 div
  document.body.removeChild(hiddenDiv);

  return width;
}

// 不同的html中的font-size不同得到的值也不同。
const theString01 = `getStringWidth('<p>Hello, Worl55555<div style="font-size:44px;">8一个</div>d!</p>')`;
const theString02 = `getStringWidth('<p>Hello, Worl55555<div style="font-size:24px;">8一个</div>d!</p>')`;
console.log(theString01, eval(theString01));//谷歌浏览器114;火狐:112;
console.log(theString02, eval(theString02));//谷歌浏览器99;火狐:89;


// 半角与全角的字符串不同,长度也不同。
const theString03 = `getStringWidth('h方!!')`;
const theString04 = `getStringWidth('he!!')`;
console.log(theString03, eval(theString03));//谷歌浏览器35;火狐:34;
console.log(theString04, eval(theString04));//谷歌浏览器30;火狐:29;
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值