jQuery 单击时切换 div 颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9714498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
toggle div color on click
提问by user348173
I have the following JS:
我有以下JS:
$(".place").mouseover(function () {
$(this).css('background-color', '#00cc00'); // green color
}).mouseout(function () {
$(this).css('background-color', '#336699'); // light blue color
});
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.
当鼠标结束时,div 变为绿色。我希望当用户点击 div 然后 div 保持绿色。如果他们再次单击,则将颜色设置为浅蓝色。我怎样才能做到这一点?
谢谢。
回答by Starx
Use .toggleClass()
function instead.
改用.toggleClass()
函数。
Usage:
用法:
$(".place").click(function () {
$(this).toggleClass("green");
});
Initially give background-color: #336699
and override this style later on with the toggleClass()
.
最初background-color: #336699
使用toggleClass()
.
Your CSS should look something like this.
你的 CSS 应该是这样的。
.place { background-color: #336699; }
.place:hover, .place.green { background-color: #00cc00; }
See this in action here.
在此处查看此操作。
Updates:
更新:
Update 1: Demowith the green in hover .
更新 1:Demo中的绿色悬停。
回答by redDevil
$(".place").click(function(){
if($(this).css('background-color')=='#00cc00')
$(this).css('background-color', '#336699');
else {
$(this).css('background-color', '#00cc00');
}
});
回答by Brian Hough
The easiest way to do this would be a toggle, perhaps using a class like this:
最简单的方法是切换,可能使用这样的类:
$(".place").click(function () {
$(this).toggleClass('green-bg');
});
Have it light blue by default, then on click it would toggle the "green-bg" class which would of course apply the green background.
默认情况下为浅蓝色,然后单击它会切换“green-bg”类,这当然会应用绿色背景。
You might have some issues with toggling both on hover and on click, I'm not sure what you want the priority to be as to what action takes precedent in assigning the bg color.
您可能在悬停和单击时切换时遇到一些问题,我不确定您希望优先级是什么,即在分配 bg 颜色时先执行哪些操作。
回答by Blender
Use CSS for the hover, not jQuery:
将 CSS 用于悬停,而不是 jQuery:
.place {
background-color: #336699;
}
.place:hover {
background-color: #00cc00;
}
And as @Starx pointed out, use .click()
.
正如@Starx 指出的那样,使用.click()
.