Jquery 单击时切换div颜色
我有以下几点:Jquery 单击时切换div颜色,jquery,css,Jquery,Css,我有以下几点: $(".place").mouseover(function () { $(this).css('background-color', '#00cc00'); // green color }).mouseout(function () { $(this).css('background-color', '#336699'); // light blue color }); 鼠标结束后,div变为
$(".place").mouseover(function () {
$(this).css('background-color', '#00cc00'); // green color
}).mouseout(function () {
$(this).css('background-color', '#336699'); // light blue color
});
鼠标结束后,div变为绿色。我想当用户点击div,然后div保持绿色。如果再次单击,则将颜色设置为浅蓝色。我该怎么做?谢谢。改用函数 用法:
$(".place").click(function () {
$(this).toggleClass("green");
});
最初给背景色:336699
,然后用toggleClass()
覆盖此样式
你的CSS应该是这样的
.place { background-color: #336699; }
.place:hover, .place.green { background-color: #00cc00; }
看看这个在行动
更新:
更新1:在悬停状态下使用绿色。在悬停状态下使用CSS,而不是jQuery:
$(".place").click(function(){
if($(this).css('background-color')=='#00cc00')
$(this).css('background-color', '#336699');
else {
$(this).css('background-color', '#00cc00');
}
});
.place {
background-color: #336699;
}
.place:hover {
background-color: #00cc00;
}
正如@Starx所指出的,使用
。click()
最简单的方法是切换,可能使用如下类:
$(".place").click(function () {
$(this).toggleClass('green-bg');
});
默认为浅蓝色,然后点击它将切换“绿色背景”类,当然会应用绿色背景
在悬停和单击时切换可能会有一些问题,我不确定您希望优先顺序是什么,以及在分配背景颜色时先采取什么操作。绿色也将悬停