单击时切换div颜色 [英] toggle div color on click

查看:109
本文介绍了单击时切换div颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JS:

 $(".place").mouseover(function () {
            $(this).css('background-color', '#00cc00'); // green color
        }).mouseout(function () {
            $(this).css('background-color', '#336699'); // light blue color
        });

当鼠标悬停时,div变为绿色.我想当用户单击div时,div保持绿色.如果再次单击,则将颜色设置为浅蓝色.我该怎么办?
谢谢.

When mouse is over then div become green. I want when user clicks on div then div persist green color. If they click again then set color to light blue. How can I do this?
Thanks.

推荐答案

使用 .toggleClass() 函数代替.

Use .toggleClass() function instead.

用法:

$(".place").click(function () {
   $(this).toggleClass("green");
});

最初提供background-color: #336699并在以后使用toggleClass()覆盖此样式.

Initially give background-color: #336699 and override this style later on with the toggleClass().

您的CSS应该看起来像这样.

Your CSS should look something like this.

.place { background-color: #336699; }
.place:hover, .place.green { background-color: #00cc00; }

请在此处中查看.

更新1 :演示,其中绿色悬停.

Update 1: Demo with the green in hover .

这篇关于单击时切换div颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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