I am trying to check for the background of an element, here is my code. But it doesn\'t work:
I tried two ways, here is the first:
function changeCol
From jQuery .css() documentation:
Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as
em
,ex
,px
or%
in a style sheet. Different browsers may return CSS color values that are logically but not textually equal, e.g.,#FFF
,#ffffff
, andrgb(255,255,255)
.
Most browsers return a rgb
value, so you can code:
if (field.css('background-color') === 'rgb(255, 177, 0)') {
// ...
}
The above snippet, based on the specified reason, may fail in some browsers. You can consider using a color conversion library or create a temporary element and set and get it's background-color
/color
property.
A simple jQuery plugin:
(function($) {
$.fn.isBgColor = function(color) {
var thisBgColor = this.eq(0).css('backgroundColor');
var computedColor = $('').css({
backgroundColor: color
}).css('backgroundColor');
return thisBgColor === computedColor;
}
})(jQuery);
Usage:
if ( field.isBgColor('#ffb100') ) {
// ...
}