Add/remove class on click to change background color of a div

半世苍凉 提交于 2021-01-27 19:27:25

问题


I've been trying to get a little black div to change color to green on click and change it back to black on the next click. I want it to keep doing this.

Unfortunately it doesn't seem to work and through checking other topics on this I couldn't find my answer.

My HTML:

<div id="block"></div>

My CSS:

   div
    {
        width: 100px;
        height: 100px;
        background-color: black;
    }

My jQuery:

  $(function(){
    $("#block").click(function(){

        if($(this).hasClass("faded") == false)
        {
            $(this).css("background-color", "green", function(){
            $(this).addClass("faded");
            });
        }
        else
        {
            $(this).css("background-color", "black", function(){
                $(this).removeClass("faded");
            });
        }
    });
    });

Basically I'm trying to let it check whether my block has a certain class, if not add it and change the background color in my css to green. If it does have the class (which it will when it's green), remove it and change the background color in my css back to black.

JSfiddle: http://jsfiddle.net/sVZtL/

Thanks in advance guys!


回答1:


Hope this fiddle helps you : http://jsfiddle.net/rachit_doshi/sVZtL/8/

$(function(){
$("#block").click(function(){

    if(!$(this).hasClass("greenDiv")) {
        $(this).addClass("greenDiv");
    } else {
        $(this).removeClass("greenDiv");
    }
});
});



回答2:


Try this:

$(document).ready(function(){
 $('#block').on('click', function() {
  $(this).toggleClass('faded');
 });
});

And put background-color: green for your faded class.

However it might not work depending on your jQuery version.

Working JSFiddle: http://jsfiddle.net/sVZtL/12/




回答3:


Hope this fiddle may help you little bit : http://jsfiddle.net/vishwa26/VCUvF/

$("div").click(function() {
//var $thisBtn = $(this);
if($("div").hasClass("btn-color")) {
    $("div").removeClass("btn-color");
    $(this).addClass("btn-color");
}
else {  
    $(this).addClass("btn-color");
}
 });


来源:https://stackoverflow.com/questions/17233270/add-remove-class-on-click-to-change-background-color-of-a-div

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