使用 Jquery,如何使用 if/else 条件改变颜色

Using Jquery, how to change color with if/else condition

其实我有2个盒子,id分别是box1和box2。

我正在使用 J-query。

我的设计:

点击box1 => 勾选box2的背景颜色,如果是黑色就改成白色,否则就改成黑色。

我的硬编码:

<body>
<div id="box1"></div>
<div id="box2"></div>
</body>

$( document ).ready(function() {
    $("#box1").click(function(){
        if ($('#box2').css({backgroundColor: 'white'})) {
            $('#box2').css({backgroundColor: 'black'});
        } else {
            $('#box2').css({backgroundColor: 'white'});
        }
    });
});

正如您将在此处的代码片段中看到的那样,jQuery 报告单元格背景颜色的 RGB 值。这种事情用 类 就容易多了。在这种情况下,您可以只使用 toggleClass()

另外,郑重声明,您的 IF 语句格式错误:

if ($('#box2').css({backgroundColor: 'white'})) {

应该是

if ($('#box2').css('background-color') ==  'white') {

...但它会失败,因为它实际上是 rgb(255, 255, 255),而不是 white

$(document).ready(function() {
  $("#box1").click(function() {
    console.log('The background color of box 2 is: ', $('#box2').css('background-color'))
    $("#box2").toggleClass('black');
  });
});
div {
  padding: 10px;
  display:inline-block;
  margin-right:10px;
  border: 1px solid #ccc;
  background-color: white;
}

.black {
  background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box1"></div>
<div id="box2"></div>