Vue獲取DOM元素樣式 && 樣式更改

在 vue 中用 document 獲取 dom 節點進行節點樣式更改的時候有可能會出現 'style' is not definde的錯誤,這時候能夠在 mounted 裏用 $refs 來獲取樣式,並進行更改:javascript

<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';
    },
相關文章
相關標籤/搜索