How to get the exact RGBa value set through CSS via Javascript?

前端 未结 1 1241
一个人的身影
一个人的身影 2020-12-31 13:04

In most browsers I\'ve tried, rgba() values seem to be changed once the browser parsed the CSS.

For example, the following CSS:

background         


        
相关标签:
1条回答
  • 2020-12-31 13:58

    Mark Hubbart's comment is correct.

    32-bit color breaks down into four 8-bit components, each within the range 0-255: red, green, blue, and alpha. We express the alpha, or transparency, as a fraction or percentage since it helps us decimal-brained folks get a quicker idea of just how transparent it is. It is actually better thought of as opaqueness (well, opacity) since 100% transparent is 0, not 1.

    Now, given 255 is the denominator for the alpha value, there is no way to express 0.5 exactly. The value you're seeing, 0.498039, comes from the nearest fraction, 127/255 (rounded to 6 decimal places). Safari returns 0.496094 which is 127/256 rounded to 6 decimal places, and to me seems a bug since that implies 257 values. I also doubt Firefox can accurately report 0.5 unless it is rounding to only 2 decimal places.

    You can work around this issue in different browsers by creating a jQuery plugin that, on first execution, checks to see what value is returned with a 50% alpha, and adjust all calculations accordingly.

    parseFloat(
       $('#divWith50PercentAlphaBackgroundStyle')
          .css('background-color')
          .split(',')[3],
       10
    )
    

    Then, with this value in hand, do a switch on it against the values different browsers return, and properly convert to the closest correct value you're expecting.

    0 讨论(0)
提交回复
热议问题