一、获取元素

1、this.$refs

2、document.querySelector()  document.getElementById() document.getElementByTagName()等等

确保获取到的元素不是undefined或null

vue中,在mounted()生命周期函数中才能获取dom元素,建议在修改样式时加个定时器,或者将代码放入 $nextTick()中执行。

二、获取元素的宽高

1、如果是内嵌样式 style="width:100px,height:100px;"

可以通过以下两种方法获取宽高:

this.$refs.ele.style.width / this.$refs.ele.style.height   获取的是字符串且带单位,如:"100px"

this.$refs.ele.offsetWidth  /this.$refs.ele.offsetHeight 获取的是字符串且无单位,,如:'100'

2、如果非内嵌样式,即样式写在样式表里面:

只能通过以下方式获取宽高:

this.$refs.ele.offsetWidth  /this.$refs.ele.offsetHeight 获取的是字符串且无单位,,如:'100'

三、给元素宽 高赋值:

1、offsetWidth / offsetHeight 是只读属性,不能赋值;

2、可以通过以下方式赋值:

this.$refs.ele.style.width = "100px";  //记得带单位

this.$refs.ele.style.height= "100px"; //记得带单位

四、getComputedStyle API

window.getComputedStyle(this.$refs.ele).width;

window.getComputedStyle(this.$refs.ele).height;

五、通过setAttribute来设置属性

this.$refs.ele.setAttribute('style','height:1000px');

this.$refs.ele.setAttribute('style','height:1000px');

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐