如何检查某个类是否有背景颜色,如果有,请更改背景颜色

How check some class has background color or not and change background color if it has

本文关键字:颜色 背景 如果 是否 何检查 检查      更新时间:2023-09-26

我有这样的类

 <div class="Ratsheet-destination-detail"></div>
    $(".Ratsheet-destination-detail").css("backgroundColor", #5B815B);

现在"Ratsheet-destination-detail"有红色的背景颜色。

我如何检查它是否有背景颜色,如果有,则将其背景颜色更改为"#616161"

谢谢。。。。。。。

您的颜色将作为 rgb 值返回。因此,请检查背景颜色的 rgb 值。如果其红色rgb(255, 0, 0),请将其更改为绿色。

var el = $('.Ratsheet-destination-detail');
if(el.css('background-color') == 'rgb(255, 0, 0)'){
    el.css('background-color','green');
}​

现场演示

通过操作的编辑,如果我理解正确,这应该可以工作。如果 bg 为红色或灰色,这会将其更改为绿色。

var el = $('.Ratsheet-destination-detail');
if(el.css('background-color') == 'rgb(97, 97, 97)' || el.css('background-color') == 'rgb(255, 0, 0)'){
    el.css('background-color','green');
}​

现场演示 2

$.css 方法将告诉您匿名函数中的旧颜色是什么:

$(".Ratsheet-destination-detail").css("background-color", function( index, old ){
  // If current is red, set to green, else set to red
  return $.Color(old).is("red") ? "green" : "red" ;
});

在这里,我正在使用jQuery Color插件,$.Color()帮助处理颜色。没有它,您将不得不处理 RGB(或可能的 RGBA)格式的颜色,例如 rgb(255, 0, 0) ,这有时会有点令人困惑。

演示:http://jsbin.com/egemaf/2/edit

为了使用jQuery Color插件,你需要从项目中下载并引用源代码,就像使用jQuery一样(假设你没有使用CDN):

<!DOCTYPE html>
<html>
  <head>
    <title>Swapping Background Colors with jQuery and jQuery Color</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
    <script src="https://raw.github.com/jquery/jquery-color/master/jquery.color.js"></script>
  </head>
  <body>
    <div class="Ratsheet-destination-detail">
      <p>Hello, World.</p>
    </div>
    <script>
    $(function(){
      $(".Ratsheet-destination-detail").css("background-color", function(i, old){
        // If current is red, set to green, else set to red
        return $.Color(old).is("red") ? "green" : "red" ;
      });
    });
    </script>
  </body>
</html>