【问题标题】:How check some class has background color or not and change background color if it has如何检查某个类是否有背景颜色,如果有则更改背景颜色
【发布时间】:2012-05-23 04:57:26
【问题描述】:

我有这样的课

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

现在“Ratsheet-destination-detail”的背景颜色为红色。

我如何检查它是否有背景颜色,如果有,然后将其背景颜色更改为“#616161”

谢谢.......

【问题讨论】:

标签: javascript jquery


【解决方案1】:

$.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 plugin$.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>

【讨论】:

  • @Loktar 在设置任何颜色之前,jQuery will report rgba(0, 0, 0, 0) 作为背景颜色。这是我的错误。
  • @yaha 如果你想使用$.Color,你需要像使用jQuery一样在你的页面上添加&lt;script/&gt;对它的引用。
  • @yaha 请参阅我的答案底部以获取设置说明。
【解决方案2】:

您的颜色将以 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');
}​

Live Demo

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

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');
}​

Live Demo 2

【讨论】:

  • @yaha 不确定这是否是您所追求的,但我已经更新了我的答案。
猜你喜欢
  • 2021-03-07
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多