jQuery - 单击时更改颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7917831/
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
jQuery - Change color on click
提问by skolind
I'm looking at some jQuery because I want to create a div that changes color when you click it.
我正在查看一些 jQuery,因为我想创建一个在单击它时会改变颜色的 div。
And I've done that with:
我已经做到了:
$(function() {
$('.star').click(function(){
$(this).css('background', 'yellow');
});
});
And it works perfectly! But I want it to remove the background color, when you click it one more time. Is that possible, and how would you do something like that?
它完美地工作!但是我希望它在您再次单击它时删除背景颜色。这可能吗,你会如何做这样的事情?
回答by Tomalak
Create a CSS class:
创建一个 CSS 类:
.clicked {
background-color: yellow;
}
and then simply toggle that classit via jQuery:
然后简单地通过 jQuery切换该类:
$('.star').click(function(){
$(this).toggleClass('clicked');
});
回答by Danielle Stone
You could set a flag in your click function, Then add an if statement
您可以在点击功能中设置一个标志,然后添加一个 if 语句
if hasBeenClicked = true;
//...background color remove
else
//....background color changed to yellow
hasBeenClicked = true;
回答by Jon
Creating a CSS class would be my suggestion as well, but you can also do this to "unset" the yellow background:
创建一个 CSS 类也是我的建议,但您也可以这样做以“取消设置”黄色背景:
$(this).css('background', 'inherit');