【问题标题】:VueJs - Change div color with transitionVueJs - 使用过渡更改 div 颜色
【发布时间】:2019-02-19 21:18:32
【问题描述】:

我有一个标题栏和一个按钮。我可以在单击时更改颜色,但我希望颜色更改具有平滑过渡或单击效果。 Vue.js 可以做到吗?

HTML 代码

<html>    
    <head>
      <title>My App</title>
    </head>
    <body>
        <div id="app">
            <div class="head" :class="{ headnew : change }"></div>
            <button @click="changeIt">Change me!</button>
        </div>
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> 
    </script>
</html>

CSS 代码

.head {
    background: linear-gradient(-90deg, #84CF6A, #16C0B0);
    height: 60px;
    margin-bottom: 15px;
  }

.headnew {
    background: red;
    height: 60px;
    margin-bottom: 15px;
}

JS 代码

var app = new Vue({
    el: "#app",
    data: {
        change : false
    },
    methods: {
        changeIt() {
            this.change = true
        }
    }
})

【问题讨论】:

    标签: javascript css vue.js vuejs2


    【解决方案1】:

    背景渐变无法设置动画,但您可以通过淡入与背景重叠的另一个元素(在本例中为 ::before 伪元素)来破解它。

    这是一个通用的 HTML+CSS 示例,您可以轻松地适应您的代码:

    .box {
      width: 100px;
      height: 100px;
      background: linear-gradient(to top, blue, yellow);
      position: relative;
      z-index: 0;
    }
    
    .box::before {
      content: '';
      position: absolute;
      z-index: -1;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      background-color: red;
      opacity: 0;
      transition: opacity 0.2s linear;
    }
    
    .box:hover::before {
      opacity: 1;
    }
    &lt;div class="box"&gt;Some text&lt;/div&gt;

    【讨论】:

    • 是的,这就是我需要的,但我希望转换是在单击按钮时进行的,我不知道 Vue 是否可以处理伪属性。
    • 这就是为什么我提到你需要根据你的情况调整它(而不是.box:hover,你会使用.headnew,例如)。您的问题与 Vue 无关;到目前为止,您拥有的 Vue 代码很好。这都是关于 CSS 的。
    【解决方案2】:

    您只需将transition 属性添加到您的.head 即可,如下所示:

      .head {
      ...
        transition: background 6s ease;
       }
    

    检查以下工作解决方案:

    var app = new Vue({
      el: "#app",
      data: {
          change : false
      },
      methods: {
          changeIt() {
              this.change = true
          }
      }
    })
    .head {
        background: linear-gradient(-90deg, #84CF6A, #16C0B0);
        height: 60px;
        margin-bottom: 15px;
        transition: background 6s ease;
      }
    
    
    .headnew {
        background: red;
        height: 60px;
        margin-bottom: 15px;
    }
      <div id="app">
        <div class="head" :class="{ headnew : change }"></div>
        <button @click="changeIt">Change me!</button>
    </div>
      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2019-07-09
      • 2020-12-31
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多