最近经常遇到一个需求就是,两个标签然后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,以便默认选中第二个按钮。
多个标签切换也可以通过这个方法来实现
不喜勿喷,欢迎指教