vue中js操作dom获取属性值刷新后无法获取。

项目开发中需要用js操作dom元素获取元素高度值后进行操作,使用的是原生的方法,在页面第一次加载和刷新页面时会出现无法获取到元素的高度值,在其他页面跳转过来时则可以获得高度值。

<template>
    <img src="../assets/diagram/bottom.png" class="imgBox" ref="bottomImg" />
</template>
<script>
    methods:{
        getHeigth(){
            var bottomHeight = document.getElementsByClassName("imgBox")[0].offsetHeight;
            console.log(bottomHeight);
        }
    },    
    mounted(){
        this.getHeigth();
        window.onresize = () =>{
            this.getHeigth();
        }
    }
<script>

在其他页面跳转过来可以输出高度,页面尺寸变化时也可以正常获取,只有在此页面刷新则无法获取高度。
而且最奇怪的时如果我console.log(document.getElementsByClassName("imgBox"));是有height值且正确的,但是无论我获取这个值的height还是offsetHeight属性都是0。

阅读 4.6k
2 个回答

你在图片@load后在获取试试 或者在@load事件中加$nexttick

在mounted中获取DOM的高度需要有一个延迟获取

mounted(){
   this.$nextTick(() => {
     this.getHeigth();
   });
   window.onresize = () =>{
     this.getHeigth();
   }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题