有人可以帮助我,我很难找出如何删除/添加垂直菜单的活动类吗?
HTML
<ul class="vertical__menu">
<li>
<a class="vertical__menu-item--active" href="#">Truck Route</a>
</li>
<li>
<a class="vertical__menu-item" href="#">Location Map</a>
</li>
<li>
<a class="vertical__menu-item" href="#">Major Retailers Map</a>
</li>
</ul>
CSS
.vertical__menu-item {
color: blue
}
.vertical__menu-item--active {
color: red
}
JQUERY
$(document).ready(function () {
$('ul.vertical__menu li a').click(function () {
$('vertical__menu-item').removeClass("--active");
$(this).addClass("--active");
});
});
答案 0 :(得分:2)
您需要在代码中添加/删除类.vertical__menu-item--active
,目前您正在删除css中不存在的类--active
。您还没有选择当前在jquery中的项目,并且您在标记中的第一个列表项上缺少.vertical__menu-item
,因此当您尝试删除.vertical__menu-item--active
类时,它将不会被选中,查看下面的工作演示:
$(document).ready(function () {
$('.vertical__menu-item').click(function () {
$('.vertical__menu-item').removeClass("vertical__menu-item--active ");
$(this).addClass("vertical__menu-item--active ");
});
});
.vertical__menu-item {
color: blue
}
.vertical__menu-item--active {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="vertical__menu">
<li>
<a class="vertical__menu-item vertical__menu-item--active" href="#">Truck Route</a>
</li>
<li>
<a class="vertical__menu-item" href="#">Location Map</a>
</li>
<li>
<a class="vertical__menu-item" href="#">Major Retailers Map</a>
</li>
</ul>
答案 1 :(得分:2)
您必须从之前的有效元素中删除该类,然后将其添加到新的类中,考虑完整的类名,而不仅仅是其后缀--active
:
$(document).ready(function() {
$('ul.vertical__menu li a').click(function() {
/*Select only the active element without forgeting the '.' */
$('.vertical__menu-item--active').removeClass("vertical__menu-item--active");
/*Adding the class to the current one*/
$(this).addClass("vertical__menu-item--active");
});
});
.vertical__menu-item {
color: blue
}
.vertical__menu-item--active {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="vertical__menu">
<li>
<a class="vertical__menu-item--active" href="#">Truck Route</a>
</li>
<li>
<a class="vertical__menu-item" href="#">Location Map</a>
</li>
<li>
<a class="vertical__menu-item" href="#">Major Retailers Map</a>
</li>
</ul>
答案 2 :(得分:2)
为什么不将vertical__menu-item
分隔为active
<强> HTML 强>
<ul class="vertical__menu">
<li><a class="vertical__menu-item active" href="#">Truck Route</a></li>
<li><a class="vertical__menu-item" href="#">Location Map</a></li>
<li><a class="vertical__menu-item" href="#">Major Retailers Map</a></li>
</ul>
<强>的style.css 强>
.vertical__menu-item {
color: blue
}
.vertical__menu-item.active {
color: red
}
<强> jquery的强>
$(document).ready(function () {
$('ul.vertical__menu li a').click(function () {
$('.vertical__menu-item').removeClass("active");
$(this).addClass("active");
});
});