Why does jQuery.css ('background-color') return rgba (0,0,0,0) for 'transparent'?

I have a field here - http://jsfiddle.net/U68p3/2/ - with a transparent background. When I read the background with jQuery.css ('background-color'), it returns

rgba(0, 0, 0, 0) 

which is not very useful if my code is looking for a match with "transparent".

Why is jQuery doing this, and is there a way to make it return transparent?

Thanks.

 $(function() { var bkgnd = $('#box').css('background-color'); console.log('background-color is ' + bkgnd); }); 
+6
source share
3 answers

This is not jquery, the calculated value for the color is represented in RGBa (red, blue, green, alpha for opacity), and not as color names (for example, red, blue, orange, transparent, etc.) or as hexadecimal values. According to the specification, transparency is represented as rgb(0, 0, 0) .

if the value is translucent, the corresponding rgba () will be the calculated value. If it is not, it will be the corresponding rgb (). The transparent keyword matches rgb (0,0,0).

So instead of looking for that particular value, you can add a specific CSS rule to enable transparency and add this class to the element, and use .hasClass or .is this class to check the transparency of the element.

It seems that different browsers present it differently, IE, FF gives the value as transparency , so it's better not to rely on this representation of the value for any logic.

+8
source

This is not jQuery. jQuery returns what the browser gives it for the calculated value (for example, from getComputedStyle or currentStyle ). What the browser gives can be in any notation that the browser wants to use. In this case, the browser you are testing on uses rgba (red, green, blue, alpha, opacity, 0 = transparent), which is a pretty good notation. Other browsers may just use rgb strings or even hexadecimal colors, which would be unsuccessful since none of them can correctly represent transparent .

+4
source

You cannot get the color as a name directly from jQuery.

Instead, you can use the jQuery Color plugin ( https://github.com/jquery/jquery-color ) to convert the value to its name or manually do something like that.

JsFiddle example

 $(function() { var bkgnd = $('#box').css('background-color'); console.log('background-color is ' + jQuery.Color(bkgnd).toString()); }); 

( http://jsfiddle.net/Ap6qD/1/ )

+2
source

All Articles