在'if..中使用CSS属性'background'时,无法使其工作。。else’语句。我在CSS和JQuery中尝试了所有可能的"backgroundColor"one_answers"backgroundColor"组合,但都不起作用。
有趣的是,当交换"if…"时使用另一个属性fx('width')=='500px',一切都很好。
在使用"背景"时,有什么特别的事情我应该知道吗?这是不起作用的代码——点击时div会变成黄色,甚至认为它应该变成粉红色。。
.box {
width: 500px;
height: 200px;
background: red;
}
<script src='http://code.jquery.com/jquery-latest.min.js'></script>
<script>
$(document).ready(function() {
$('.box').click(function(){
if ($('.box').css('background') == 'red') {
$('.box').css('background', 'pink');
}
else {
$('.box').css('background', 'yellow');
}
});
});
</script>
答案-这是showdev的原始答案,我认为它更好地反映了我的问题-可能会对未来的访问者有所帮助:
$('.box').click(function() {
if ($(this).css('background-color') == 'rgb(255, 0, 0)') {
$(this).css('background-color', 'pink');
} else {
$(this).css('background-color', 'yellow');
}
});
CSS background
是包括background-clip, background-color, background-image, background-origin, background-position, background-repeat, background-size, and background-attachment.
在内的几个单独背景属性的简写
结果,background
的值被返回为类似于rgb(255, 192, 203) none repeat scroll 0% 0% / auto padding-box border-box
的值。
您可以使用background-color
,但是jQuery以RGB而不是HEX返回background-color
值。因此,您需要匹配RGB值,而不是HEX或单词("红色")。
此外,我更改了单击处理程序中的引用,使其使用$(this)
,而不是再次选择框。当页面上有多个框时,这允许更大的灵活性。
$(document).ready(function() {
$('.box').click(function() {
$this = $(this);
$this.css('background-color',
$this.css('background-color') == 'rgb(255, 0, 0)' ? 'pink' : 'yellow');
});
});
.box {
width: 500px;
height: 50px;
background-color: red;
}
.box.blue {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box blue"></div>
将CSS颜色视为RGB:
-
"计算值:如果值是半透明的,则计算值将是rgba()对应的值。如果不是,则为rgb()对应值。"-Color-CSS|MDN
-
我可以强制
backgroundColor
以十六进制格式返回吗?