在vue中獲取dom元素

轉發請備註原文鏈接地址:https://www.niwoxuexi.com/blog/web/article/307.html

在vue中經常會通過js操作dom對象,可以通過給標籤添加ref屬性實現,

下面通過操作dom對象實現一個點擊按鈕改變屏幕背景的demo,效果如下



下面是代碼:

<template>
  <div class="box" ref="boxHook">
    <div class="change-button" @click="changeBackground">Click me change backgroundColor </div>
  </div>
</template>

<script type='text/ecmascript-6'>
  export default{
    methods: {
      changeBackground() {
        var R = Math.floor(Math.random() * 255)
        var G = Math.floor(Math.random() * 255)
        var B = Math.floor(Math.random() * 255)
        var color = 'rgb(' + R + ',' + G + ',' + B + ')'

        this.$refs.boxHook.style.background = color
      }
    }
  }
</script>

<style lang='stylus' rel='stylesheet/stylus'>
  .box
    width 100%
    height 100%
    background #ffffff
    padding-top 200px
    .change-button
      width 320px
      height 60px
      line-height 60px
      text-align center
      margin 0 auto
      color #ffffff
      font-size 18px
      background green

</style>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章