html部分:
<div ref="menuDiv"></div>
js部分:
1.offsetWidth 、 offsetHeight ,返回 Number 类型,例如:200。
let domWidth = this.$refs.menuDiv.offsetWidth; //宽度
let domHeight = this.$refs.menuDiv.offsetHeight; //高度
console.log(domWidth,domHeight)//打印dom的宽度,高度
2. window对象的 getComputedStyle API,返回 String 类型,包含px单位,例如:"200px"。
let domWidth = window.getComputedStyle(this.$refs.menuDiv).width; //宽度
let domHeight = window.getComputedStyle(this.$refs.menuDiv).height; //高度
console.log(domWidth,domHeight)//打印dom的宽度,高度
本文探讨了在JavaScript中如何获取DOM元素的宽度和高度,通过`offsetWidth`和`window.getComputedStyle`两种方法进行比较。`offsetWidth`直接返回元素的宽度不包括滚动条,而`getComputedStyle`则返回带有px单位的样式属性,包括边框和内填充。这两种方法在获取元素尺寸时各有特点,适用于不同的场景。
1801

被折叠的 条评论
为什么被折叠?



