我正在尝试设置我构建的菜单的样式,每次有人点击它们时,我都会在每个 div 元素上添加一个不同的类。当我单击其他 3 个 div 中的任何一个时,如何从该元素中删除已添加的类?
$('.fashion-btn').click(function() {
$(this).addClass("active-btn-red");
});
$('.garden-btn').click(function() {
$(this).addClass("active-btn-pink");
});
$('.technology-btn').click(function() {
$(this).addClass("active-btn-purple");
});
$('.auto-btn').click(function() {
$(this).addClass("active-btn-deep-purple");
});
.categories-sidebar-popup-menu-row {
padding: 10px 15px;
cursor: pointer;
display: block;
position: relative;
margin-left: 20px;
margin-right: 20px;
border-radius: 28px;
margin-bottom: 10px;
font-weight: 500;
font-size: 16px;
letter-spacing: -0.5px;
color: #555B66;
}
.active-btn-red {
background: #E53935;
color: #fff!important;
}
.active-btn-pink {
background: #D81B60;
color: #fff!important;
}
.active-btn-purple {
background: #8E24AA;
color: #fff!important;
}
.active-btn-deep-purple {
background: #5E35B1;
color: #fff!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="categories-sidebar-popup-menu-row fashion-btn">FASHION</div>
<div class="categories-sidebar-popup-menu-row garden-btn">GARDEN</div>
<div class="categories-sidebar-popup-menu-row technology-btn">TECHNOLOGY</div>
<div class="categories-sidebar-popup-menu-row auto-btn">AUTO</div>
我知道我可以为他们每个人做类似的事情:
$('.fashion-btn').click(function() {
$(this).addClass("active-btn-red");
$('.garden-btn').removeClass("active-btn-pink");
$('.technology-btn').removeClass("active-btn-purple");
$('.auto-btn').removeClass("active-btn-deep-purple");
});
但由于我将在我的菜单中添加超过 20 个元素,我想问一下是否有更智能/更短的方法来完成这项工作。
最佳答案
正如@disinfor 在评论中所说,你可以这样做:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="categories-sidebar-popup-menu-row fashion-btn" data-active-class ='active-btn-red '>FASHION</div>
<div class="categories-sidebar-popup-menu-row garden-btn">GARDEN</div>
<div class="categories-sidebar-popup-menu-row technology-btn">TECHNOLOGY</div>
<div class="categories-sidebar-popup-menu-row auto-btn">AUTO</div>
.categories-sidebar-popup-menu-row {
padding: 10px 15px;
cursor: pointer;
display: block;
position: relative;
margin-left: 20px;
margin-right: 20px;
border-radius: 28px;
margin-bottom: 10px;
font-weight: 500;
font-size: 16px;
letter-spacing: -0.5px;
color:#555B66;
}
.fashion-btn.active {
background:#E53935;color:#fff!important;
}
.garden-btn.active {
background:#D81B60;color:#fff!important;
}
.technology-btn.active {
background:#8E24AA;color:#fff!important;
}
.auto-btn.active {
background:#5E35B1;color:#fff!important;
}
$(".categories-sidebar-popup-menu-row" ).each(function (){
$(this).click(function(){
clearStyle();
$(this).addClass("active");
});
});
function clearStyle(){
buttonWithActive = $('.categories-sidebar-popup-menu-row.active');
buttonWithActive.removeClass('active');
}
关于javascript - 使用 jquery 单击多个 div 时添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58069991/