【问题标题】:Add background color when click a button vue js单击按钮时添加背景颜色vue js
【发布时间】:2020-04-08 19:14:31
【问题描述】:

我正在使用 VUE JS 构建一个应用,使用不同的组件。

在其中一个中,我有一个按钮,当我点击它时我希望它改变颜色。此按钮从表格中选择不同的项目,因此当我按下该按钮时,我希望该按钮的背景变为红色,例如以了解我点击了哪些项目。

<template>
  <button class="mdc-icon-button material-icons"  @click="doMultiple">delete_outline</button>  
</template>

这是按钮。单击按钮时如何添加样式?

提前致谢!

【问题讨论】:

  • 请通过 Vue 类和样式绑定。 vuejs.org/v2/guide/class-and-style.html
  • 您可以通过在单击该按钮时有条件地添加一个类来做到这一点。 clicked 初始值为 false 并在点击时设置为 true。
  • @Ramki 谢谢,但我已经尝试过你所说的,它在 :class 上返回一个错误,因为它说它需要一个属性值。

标签: javascript vue.js button vue-component background-color


【解决方案1】:

您可以使用条件绑定将类动态添加到元素。

https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: "#app",
  data: {
    deleteClicked: false
  },
  methods: {
    onClick() {
      this.deleteClicked = true;
    }
  }
})
.red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div :class="{ red : deleteClicked }">
    Item
    <button @click="onClick">
      Delete
    </button>
  </div>
</div>

【讨论】:

  • 谢谢,不完全是我想要的,但这可以帮助我。谢谢皮埃尔!!
  • 那么原始类呢?你如何将它保存在元素中?
  • @rjurney 你可以同时拥有静态类和动态类&lt;div class="static" :class="{ dynamic : true }"&gt;vuejs.org/v2/guide/class-and-style.html#Object-Syntax
【解决方案2】:
Call the css class with either of the option

.mdc-icon-button material-icons:active{
    background:red;
}
OR

.mdc-icon-button material-icons:focus{
    background:red;
}

【讨论】:

    【解决方案3】:

    这是我用 watch 方法将 js 变量链接到 vue js 的版本。这是即时的,并且会随着您沿颜色选择器拖动光标而改变。检查下面的代码 sn-p。还需要 CSS。

    let vue = new Vue({
      el: "#view",
      data: {
        bg: "#FFFFFF",
        color: "#000000",
      },
      watch: {
        bg: css_variable_watcher("--bg"),
        color: css_variable_watcher("--color"),
      },
    });
    //Watcher for CSS
    function css_variable_watcher(name, suffix = "") {
      return {
        immediate: true,
        handler(new_value, old_value) {
          document.documentElement.style.setProperty(name, new_value + suffix);
        },
      };
    }
    body {
      background-color: var(--bg);
      color: var(--color);
    }
    <body>
      <div id="view">
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
        <input type="color" v-model="bg">
        <input type="color" v-model="color">
        <button type="button" v-on:click="[color, bg] = [bg, color]">Swap Text and Background Color</button>
        <p>Hello. I am a Paragraph. Select the first input to change bg color and second input to change text color.</p>
      </div>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-06
      • 2014-10-09
      • 2021-03-28
      • 2017-08-02
      • 2017-01-26
      • 2014-10-10
      • 1970-01-01
      相关资源
      最近更新 更多