问题
The .highlight
class isn't working when toggled on #button
. What am I doing wrong?
HTML:
<form>
<input id="button" type="submit" value="Click Me">
</form>
CSS:
#button {
background-color: #AABF1A;
}
.highlight {
background-color: #555BBB;
}
jQuery:
$(document).ready(function () {
$("#button").click(function() {
$(this).toggleClass("highlight");
});
});
回答1:
Your jQuery code is working. The issue is that your .highlight
class does not have a high enough specificity to override the styles placed on the element by the #button
selector. Try changing your CSS to this:
#button.highlight {
background-color: #555BBB;
}
回答2:
Full code:
$(document).ready(function () {
$("#button").click(function(event) {
event.preventDefault
$(this).toggleClass("highlight");
});
});
Working fiddle: http://jsfiddle.net/robertrozas/9g8Jj/2/
来源:https://stackoverflow.com/questions/23816503/jquery-toggleclass-not-toggling-css-class