Js 精确获取Dom元素宽度/高度

本文探讨了不同浏览器下CSS像素的解析差异,详细介绍了如何通过多种方法精确获取元素的宽度和高度,包括使用window.getComputedStyle、object.getBoundingClientRect及jQuery,同时提供了一个获取字符串显示尺寸的实用函数。

css像素解析:
    四舍五入解析的浏览器:IE8、IE9、Chrome、Firefox 
    直接取整解析的浏览器:IE7、Safari

获取元素精确的宽度/高度(带小数位像素)
   问题:document.getElementById(id).style.width 只能获取元素行内样式的值
   
解决办法一:
   window.getComputedStyle(element)  返回元素所有CSS属性值

解决办法二:
   object.getBoundingClientRect()  返回元素的大小及其相对于视口的位置

解决办法三:
   jQuery $(obj).width();

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no,viewport-fit=cover">
    <title>demo</title>
    <style>
      *{margin: 0;padding:0;}
      #fir{
        display: inline-block;
        width: 74px;
        font-size: 16px;
        background-color: red;
      }
      #sec{
        display: inline-block;
        font-size: 16px;
        background-color: red;
      }
    </style>
  </head>
  <body>
      <span id="fir">测试 测试!</span><br/>
      <span id="sec">测试 测试!</span>
      <script src="../resource/jquery-3.3.1.min.js"></script>
      <script>
        /*获取元素精确的宽度/高度(带小数位像素)*/
        let firWidth = document.getElementById('fir').style.width; 
        console.log('firWidth:'+firWidth);  // firWidth: "" 无法获取元素的宽度

        let secWidth = $('#sec').width(); 
        console.log('secWidth:'+secWidth);  //  secWidth: 73.7344  只能获取元素像素整数部分的值
        let secObj = document.getElementById('sec');

        let secWidth2 = window.getComputedStyle(secObj).width;
        console.log('secWidth2:'+secWidth2);  //  secWidth2: 73.7344px  精确获取元素像素值(带像素单位)

        let secWidth3 = secObj.getBoundingClientRect().width;
        console.log('secWidth3:'+secWidth3);  //  secWidth3: 73.734375  精确获取元素像素值

        /*获取字符串显示的宽度/高度*/
        function getEleSize(fontSize,fontFamily,conent){
          let spanObj = document.createElement('span');
          let result = {};
          spanObj.style.fontSize = fontSize;
          spanObj.style.fontFamily = fontFamily;
          spanObj.style.visibility = "hidden";
          spanObj.style.display = "inline-block";
          document.body.appendChild(spanObj);
          spanObj.textContent = conent;
          result.width = parseFloat(window.getComputedStyle(spanObj).width);
          result.height = parseFloat(window.getComputedStyle(spanObj).height);
          return result;
        }
        let eleWidth = getEleSize('16px','','测试 测试!').width; 
        console.log('eleWidth:'+eleWidth); // 可与 #sec 对比
      </script>
  </body>
</html>

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值