问题
I have a single page site. My navigation consists of a few buttons styled by bootstrap 3.
Since it is a single page, the buttons are anchor tags. I want to be able to have an .active class applied to the last anchor tag that has been clicked.
This is my HTML:
<a href="#home">
<button type="button" class="btn btn-default btn-lg active">
<span class="glyphicon glyphicon-home"></span> Home
</button>
</a>
<a href="#about">
<button type="button" class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-user"></span> About
</button>
</a>
And my CSS:
.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
border:none;
background-color: #2C3E50;
border-bottom: 1px solid #2C3E50;
}
回答1:
Try this...
$(function() {
$("a").on("click", function() {
$(".btn-default.active").removeClass("active");
$(this).find(".btn-default").addClass("active");
});
});
or...
$(function() {
$("a").on("click", function() {
$("a.active").removeClass("active");
$(this).addClass("active");
});
});
Not sure if the active class should be added to the link or the enclosed button, so there's 1 for each.
回答2:
You could use jQuery addClass
$('a#buttonid').click(function(){
$(this).addClass('active');
});
You'd check to make sure it doesn't already have that class and remove the active class from the other buttons aswell.
来源:https://stackoverflow.com/questions/19142653/adding-removing-class-to-anchor-tag-with-jquery-twitter-bootsrap-buttons