简介
JS获取元素宽高时,有的获取不到想要的值。
借鉴原文:链接地址 >
具体实现
// HTML
<div id="documentLabel " style="height: 100px;"></div>
// CSS
#documentLabel {
background-color: aquamarine;
width: 100px;
}
1.el.style.width/height
注意:style对象只能获取内联样式(dom中的style里的样式)
const el= document.getElementById('documentLabel')
console.log(el.style.width) // "" style对象取不到 style标签中定义的样式
console.log(el.style.height) // "100px"
2.window.getComputedStyle(element).width/height
window.getComputedStyle()可以实时获得style属性
MDN参考资料
const el = document.getElementById('documentLabel')
console.log(window.getComputedStyle(el).width)
console.log(window.getComputedStyle(el).height)
3.Element.getBoundingClientRect().width/height
MDN参考资料
const el = document.getElementById('documentLabel')
console.log(el.getBoundingClientRect().width)
console.log(el.getBoundingClientRect().height)
4.元素上的其他属性字段
const el = document.getElementById('documentLabel')
console.log(el.clientWidth) // 可见区域宽
console.log(el.clientHeight) // 可见区域高
console.log(el.offsetWidth) // 可见区域宽 + 边线的宽
console.log(el.offsetHeight) // 可见区域高 + 边线的宽
console.log(el.scrollWidth) // 正文全文宽
console.log(el.scrollHeight) // 正文全文高
console.log(el.screenTop) // 被卷去的高
console.log(el.scrollLeft) // 被卷去的左
拓展
关于浏览器的几个属性
console.log(window.screenTop) // 网页正文部分上
console.log(window.screenLeft) // 网页正文部分左
console.log(window.screen.height) // 屏幕分辨率的高
console.log(window.screen.width) // 屏幕分辨率的宽
console.log(window.screen.availHeight) // 屏幕可用工作区高度
console.log(window.screen.availWidth) // 屏幕可用工作区宽度
最后
觉得有用的朋友请用你的金手指点一下赞,或者评论留言一起探讨技术!