2012-05-15 66 views
1

有這樣我如何查一些類具有背景色或不和改變背景顏色,如果它有

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

現在「Ratsheet目的地細節」類有紅色的背景色。

如何檢查這有背景顏色,如果它已經然後改變它的背景色爲「#616161」

謝謝.......

+0

類似於:http://stackoverflow.com/questions/1160617/jquery-if-then-statement-for-css-value –

+0

能否請您查看此http://stackoverflow.com/questions/ 10411187/how-to-check-the-background-color-of-an-element-using-jquery – Kashiftufail

回答

1

你的顏色會回來的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

與OP的編輯本應該工作,如果我理解正確。如果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'); 
}​ 

Live Demo 2

+0

請現在回答我 – yaha

+0

@yaha不知道這是什麼y你之後,但我更新了我的答案。 – Loktar

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的顏色插件,你需要下載和從您的項目中引用的來源,就像你使用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> 
+0

不工作。顏色以rgb的形式返回,而不是rgba。 – Loktar

+0

@Loktar在設置任何顏色之前,[jQuery將報告](http://jsbin.com/iqureb/edit#javascript,html)'rgba(0,0,0,0)'作爲背景顏色。這是我的錯誤。 – Sampson

+0

啊確定這很奇怪。 – Loktar