【问题标题】:Vue JS - How to create a color switcher using buttonsVue JS - 如何使用按钮创建颜色切换器
【发布时间】:2021-07-29 11:14:10
【问题描述】:

我有两个按钮我想这样做,当按下第一个按钮时,它的背景会发生变化(例如,红色)并且第二个按钮的背景颜色变为白色,反之亦然,当按下第二个按钮时,第二个按钮的背景色变为红色,第一个按钮的颜色变为白色

<template>
  <div class="btn-group">
    <div>
      <button>First Click</button>
    </div>
    <div>
      <button>Second Click</button>
    </div>
  </div>
</template>

<script>
export default {
  isCheck: false,
};
</script>

<style scoped>
   .btn-group div button {
      background: white;
      color: red;
      padding: 10px;
   }
</style>

你也可以看到给定的code in codesandbox

我编辑了我的问题,忘了强调两个细微差别,按钮的初始背景颜色是白色,此外,当您单击特定按钮时,按钮文本颜色应该会改变,当您单击时,原始按钮颜色是红色单击它,文本颜色应变为白色

【问题讨论】:

    标签: javascript vue.js vuejs2 boolean


    【解决方案1】:

    您可以使用状态变量并相应地将 css 类应用于您的按钮,例如:

    <template>
      <div class="btn-group">
        <div>
          <button
          :class="{ red: state === 1, white: state === 2 }"
          @click="setState(1)"
          >First Click</button>
        </div>
        <div>
          <button
          :class="{ red: state === 2, white: state === 1 }"
          @click="setState(2)"
          >Second Click</button>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: "HelloWorld",
      isCheck: false,
      props: {
        msg: String,
      },
      data() {
        return {
          state: 0
        }
      },
      methods: {
        setState(s) {
          this.state = s;
        }
      }
    };
    </script>
    
    <style scoped>
    .btn-group {
      display: flex;
      justify-content: center;
    }
    button {
      background: white;
      color: red;
      padding: 10px;
    }
    .red {
      background: red;
      color: white;
    }
    .white {
      background: white;
      color: red;
    }
    </style>
    

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 2021-08-29
      • 2011-09-11
      • 2020-01-05
      • 2021-10-04
      • 2013-06-07
      • 2017-02-07
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多