vue获取dom元素的宽高

本文探讨了在JavaScript中如何获取DOM元素的宽度和高度,通过`offsetWidth`和`window.getComputedStyle`两种方法进行比较。`offsetWidth`直接返回元素的宽度不包括滚动条,而`getComputedStyle`则返回带有px单位的样式属性,包括边框和内填充。这两种方法在获取元素尺寸时各有特点,适用于不同的场景。
摘要由CSDN通过智能技术生成

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的宽度,高度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值