js获取精确宽度/高度(带小数位像素)

问题:用jquery获取div等块级元素的宽高时不能精确获取,只能得到整数部分像素,不能获取小数位px。请看下面事故:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
</head>
<body>
    <span id="test" style="display: inline-block;">测试 Test!</span>
    <script src="jquery.min.js"></script>
    <script>
      console.log($("#test").width());
    </script>
</body>
</html>

结果是:
实际得宽度
这是span实际的宽度73.36px,而控制台打印出来的结果是下面这张图:
jquery获取的宽度
jquery获取的宽度只有73px !!!

既然jquery不能精确获取宽度,那原生js可以吗?使用document.getElementById("test").style.width 可以吗,肯定是不行的,这个方法只能获取css内联样式表里定义好的样式,这里span的内容是不固定的,所以这个方法不行。

解决方法1

window.getComputedStyle()

使用方法:window.getComputedStyle(element)

这个方法是js里提供元素属性最全的方法,里面包含几百个属性,我们把它在控制台打印出来console.log(window.getComputedStyle(document.getElementById("test")));

元素属性
打印出来的是一个对象,在最后我们看到width属性为73.3594px,比浏览器解析的还精确。

解决方法2

getBoundingClientRect()

使用方法:element.getBoundingClientRect()
我们直接在控制台打印:$("#test")[0].getBoundingClientRect(),结果如图:

getBoundingClientRect结果
这里我们看到,不仅有width,height的精确值,还有元素的文档中的位置。这个函数在页面滚动到固定元素提供很好的方案,需要的可以自己试一试。

猜你喜欢

转载自blog.csdn.net/zy1281539626/article/details/78488062
今日推荐