单击按钮Vue JS时添加背景色

时间:2019-12-16 10:25:23

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

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

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

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

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

谢谢!

3 个答案:

答案 0 :(得分:1)

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;
}

答案 1 :(得分:0)

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

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>

答案 2 :(得分:0)

这是我使用watch方法将js变量链接到vue js的版本。这是立即的,并且随着您沿着颜色选择器拖动光标而改变。检查下面的代码段。 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>

相关问题