JS:获取元素宽高的几种方式

简介

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) // 屏幕可用工作区宽度

最后

觉得有用的朋友请用你的金手指点一下赞,或者评论留言一起探讨技术!

  • 36
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值