获取网页窗体方法
1 | // 网页可见区域宽(可变): |
获取DOM元素的宽高
元素的实际高度:
1 | document.getElementById("div").offsetHeight |
元素的实际宽度:
1 | document.getElementById("div").offsetWidth |
元素的实际距离左边界的距离:
1 | document.getElementById("div").offsetLeft |
元素的实际距离上边界的距离:
1 | document.getElementById("div").offsetTop |
Element.getBoundingClientRect().width/height
除了能够获取宽高,还能获取元素位置等信息
MDN参考资料
1 | console.log(ele.getBoundingClientRect().width); // 100 |
Canvas宽高获取
canvas 元素的宽度
1 | canvas.offsetWidth; |
canvas 画布的宽度
1 | canvas.width; |
scrollWidth/clientWidth/offsetWidth的区别
scrollWidth:对象的实际内容的宽度,不包边线宽度,会随对象中内容超过可视区后而变大。
clientWidth:对象内容的可视区的宽度,不包滚动条等边线,会随对象显示大小的变化而改变。
offsetWidth:对象整体的实际宽度,包滚动条等边线,会随对象显示大小的变化而改变
获取DOM的样式
Element.style.width/height
只能获取内联样式
1 | var ele = document.getElementById('element'); |
window.getComputedStyle(ele).width/height
可获取实际生效的样式
获取的宽度可能是80%
这样的值
1 | console.log(window.getComputedStyle(ele).width); // '100px' |
Element.currentStyle.width/height
功能与getComputedStyle
相同,只存在于旧版本IE中(IE9以下),除了做旧版IE兼容,就不要用它了。