在if语句中检查背景颜色 [英] Check background color in if statement
问题描述
我有一个如果
语句与2条件。由于某种原因,它将背景颜色更改为红色,从不变为黑色。
I have an if
statement with 2 conditions. For some reason it changes the background color to red and never to black.
$(".circles").click(function() {
counter++;
if (counter % 2 === 0 && $(this).css("background-color")=="#FFFFFF") {
$(this).css("background-color", "black");
} else {
$(this).css("background-color", "red");
}
})
.circles
最初设置为 #FFFFFF
。
有什么问题?
The .circles
is set to #FFFFFF
originally.
What is wrong?
推荐答案
浏览器可能会给你回来 rgb
使用 css(background-color)
方法,但这不是肯定的。如果你想确定,比创建一个白色背景的元素,并获得其属性:
The browser will probably give you back the rgb
color if you use css("background-color")
method, but that is not for sure. If you want to be sure, than create an element with white background and get its property:
var whiteColor = $('<div/>').css({
backgroundColor: '#fff'
}).css('backgroundColor');
var counter = 0;
$(".circles").click(function() {
counter++;
if (counter % 2 === 0 && $(this).css("background-color") == whiteColor) {
$(this).css("background-color", "black");
} else {
$(this).css("background-color", "red");
}
})
.circles {
background-color: #FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circles" style="background-color: #fff;">
Click me
</div>
http://stackoverflow.com/questions/12124451/jquery-if-background-color#answer-12124493\">此答案。
Credits to this answer.
也在< a href =https://jsfiddle.net/ywx5pjgg/1/ =nofollow>这个小提琴。
这篇关于在if语句中检查背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!