单击添加/删除类以更改 div 的背景颜色 [英] Add/remove class on click to change background color of a div

查看:46
本文介绍了单击添加/删除类以更改 div 的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试让一个黑色的 div 在点击时将颜色更改为绿色,并在下次点击时将其更改回黑色.我希望它继续这样做.

不幸的是,它似乎不起作用,通过检查其他主题,我找不到我的答案.

我的 HTML:

我的 CSS:

 div{宽度:100px;高度:100px;背景颜色:黑色;}

我的 jQuery:

 $(function(){$("#block").click(function(){if($(this).hasClass("faded") == false){$(this).css("背景色", "绿色", function(){$(this).addClass("褪色");});}别的{$(this).css("background-color", "black", function(){$(this).removeClass("褪色");});}});});

基本上我试图让它检查我的块是否有某个类,如果没有添加它并将我的css中的背景颜色更改为绿色.如果它确实有这个类(当它是绿色的时候它会),删除它并将我的 css 中的背景颜色更改回黑色.

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

提前谢谢各位!

解决方案

希望这个小提琴能帮到你:http://jsfiddle.net/rachit_doshi/sVZtL/8/

$(function(){$("#block").click(function(){if(!$(this).hasClass("greenDiv")) {$(this).addClass("greenDiv");} 别的 {$(this).removeClass("greenDiv");}});});

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!

解决方案

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");
    }
});
});

这篇关于单击添加/删除类以更改 div 的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆