两个标签用动态类 active 来切换样式

最近经常遇到一个需求就是,两个标签然后hover到另一个就切换样式。一般默认选中其中一个标签

样式图

html

<div class="buttonBox">
        <div class="btn1" :class="getClass(1)" @mouseover="setActive(1)">
          免费试用
        </div>
        <div class="btn2" :class="getClass(2)" @mouseover="setActive(2)">
          在线咨询
        </div>
</div>

css

.buttonBox {
      width: 370px;
      height: 40px;
      position: absolute;
      bottom: 70px;
      left: 50%;
      margin-left: -185px;
      display: flex;
      justify-content: space-between;
      .btn1,
      .btn2 {
        width: 138px;
        height: 39px;
        line-height: 38px;
        border-radius: 39px;
        text-align: center;
        font-size: 16px;
        background-color: #fff;
        color: #c70001;

        &.active {
          background-color: #c70001;
          color: #fff;
         }
     }
}

js代码

export default {
  data() {
    return {
      activeButton: 2,
    };
  },
  methods: {
    setActive(buttonNumber) {
      this.activeButton = buttonNumber;
    },
  },
  computed: {
    getClass() {
      return (buttonNumber) => ({
        active: this.activeButton === buttonNumber,
      });
    },
  },
};

在上面的代码中,我们使用了一个  activeButton 变量来跟踪当前选中的按钮。我们通过计算属性 getClass 来返回一个函数,该函数接收按钮编号作为参数,并根据 activeButton 的值来决定是否添加 active 类。当鼠标悬停在按钮上时,我们调用 setActive 方法来更新 activeButton 的值。

默认情况下,我们将activeButton的初始值设为2,以便默认选中第二个按钮。

多个标签切换也可以通过这个方法来实现

不喜勿喷,欢迎指教

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值