获取元素宽高


获取元素宽高

一、只能获取内联样式

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

二、可获取实时的style

MDN资料javascript

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

三、Element.currentStyle.width/height

功能与第二点相同,只存在于旧版本IE中(IE9如下),除了作旧版IE兼容,就不要用它了。java

四、除了可以获取宽高,还能获取元素位置等信息

MDNcode

var ele = document.getElementById('element');
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100
相关文章
相关标签/搜索