该.css
方法在不同的浏览器中有不同的输出:
$('<div>').css('background-color', 'red').css('background-color');
// Google Chrome
// "red"
// Mozilla Firefox
// "rgb(255, 0, 0)"
另一个例子:
$('<div>').css('background-color', 'rgba(0, 0, 0, 0)').css('background-color');
// Google Chrome
// "rgba(0, 0, 0, 0)"
// Mozilla Firefox
// "transparent"
解决方案
Working FIDDLE Demo
创建一个对象来存储所有可能情况下的所有颜色:
var colors = {
'red' : ['red' , '#FF0000', '#ff0000', 'rgb(255, 0, 0)', 'rgba(255, 0, 0, 1)'],
'green': ['green', '#00ff00', '#00FF00', 'rgb(0, 255, 0)', 'rgba(0, 255, 0, 1)']
// etc
};
现在您可以使用$.inArray
方法进行比较:
HTML
<div id="test1" style="background-color: red;">I am RED</div>
<div id="test2" style="background-color: blue;">I am Blue</div>
JS
// you want to see if `elem_color` is `red`
// just like this: elem_color == 'red'
var elem_color = $('#test1').css('background-color');
if ($.inArray(elem_color, colors['red']) > -1) {
alert('Element is RED');
}
// you want to see if `elem_color` is not `green`
// just like this: elem_color != 'green'
var elem_color = $('#test2').css('background-color');
if (! ($.inArray(elem_color, colors['green']) > -1)) {
alert('Element is not GREEN');
}