Vue获取DOM元素样式 && 样式更改


在 vue 中用 document 获取 dom 节点进行节点样式更改的时候有可能会出现 'style' is not definde的错误,这时候可以在 mounted 里用 $refs 来获取样式,并进行更改:

<template>
  <div style="display: block;" ref="abc">
    <!-- ... -->
  </div>
</template>
<script>
  export default {
    mounted () {
      console.log(this.$refs.abc.style.cssText)
    }
  }
</script>

结果是 display: block;
如果我们给一个div设定全屏背景图,就需要获取屏幕高度进行赋值:
<template>
  <div ref="nana">
    <!-- ... -->
  </div>
</template>

<script>
export default {
  mounted () {
   let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
   let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    this.$refs.nana.style.height = h +'px';

  }

}

</script>

 备注:有必要时需要在updated方法中设置

    updated () {
      let height = this.$refs.luckDraw.offsetHeight;
      this.$refs.luckDrawContainer.style.height= height+'px';
    },

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM