jQuery .toggleClass not toggling CSS class

女生的网名这么多〃 提交于 2021-02-16 20:11:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!