Highlighting and Toggling between links - How to set the default class
Good day everyone!
I have this piece of code I am trying to get to work. I have been searching this forum, came pretty close but can get it.
I am trying to toggle between links to highlight the current link.
This has been disc开发者_如何学JAVAussed on here, however I can't seem to find a solution that matches my problem.
I manage to get the link to toggle, add class and remove class.
What I am confused about is how do I assigned a default class.
Meaning I would like to give the links a default style, then override it with the add/remove class toggle.
Currently the links are not styled on default, if I style them directly with CSS, then the script does not work. That's because I cannot find a way to remove that style.
Code:
$(document).ready(function() {
$("#test a").click(function () {
$(".normal").removeClass("normal");
$(this).toggleClass('normal');
});
});
The HTML:
<div id="test">
<a href="#">Testing</a>
<a href="#">Testing</a>
<a href="#">Testing</a>
</div>
The Solution: To make this work I simply placed CSS !important declaration on the style I want to override. Because the default style is place directly on the selector, it does not allow any other style to take over. Meaning, If you apply two styles to one element, the direct style takes the charge.
CSS
.active{/*SETS THE ACTIVE STYLE*/
color: #333 !important;
text-decoration: none;
font-size: 16px;
}
#test a{ /*SETS THE DEFAULT STYLE*/
color: #666;
text-decoration: none;
font-size: 16px;
}
The JQuery:
$(document).ready(function() {
$("#test a").click(function () {
$(".normal").removeClass("active");
$(this).toggleClass('active');
});
});
The HTML:
<div id="test">
<a href="#">Testing</a>
<a href="#">Testing</a>
<a href="#">Testing</a>
</div>
Just do it with plain old css :)
<a href="#" class="foo">Testing</a>
That will give each one a default class.
EDIT just re-read your question, still use the CSS and then if you do something like:
$("a").removeClass();
It should remove all classes.
精彩评论