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

您所在的位置:网站首页 js设置元素宽度怎么设置出来 JS:获取元素宽高的几种方式

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

2024-02-08 03:57| 来源: 网络整理| 查看: 265

简介

JS获取元素宽高时,有的获取不到想要的值。 借鉴原文:链接地址 >

具体实现 // HTML // 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) // 屏幕可用工作区宽度 最后

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3