<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