js獲取元素寬高的幾種方法


<style>
    #element {
        background-color: aquamarine;
        width: 100px;
    }
</style>
<div id="element" style="height: 100px;"></div>

1、Element.style.width/height

只能獲取內聯樣式

var ele = document.getElementById('element');
console.log(ele.style.width); // 空字符串
console.log(ele.style.height); // '100px'

2、window.getComputedStyle(ele).width/height

可獲取實時的style
MDN參考資料

var ele = document.getElementById('element');
console.log(window.getComputedStyle(ele).width); // '100px'
console.log(window.getComputedStyle(ele).height); // '100px'

3、Element.currentStyle.width/height

功能與第二點相同,只存在於舊版本IE中(IE9以下),除了做舊版IE兼容,就不要用它了。

4、Element.getBoundingClientRect().width/height

除了能夠獲取寬高,還能獲取元素位置等信息
MDN參考資料

var ele = document.getElementById('element');
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM