How to extract r, g, b, a values from CSS color?

后端 未结 7 482
猫巷女王i
猫巷女王i 2021-01-08 00:54

What would be the easiest way to transform

$(\'#my_element\').css(\'backgroundColor\')

to object like this:

{ r: red_value,         


        
7条回答
  •  悲&欢浪女
    2021-01-08 01:02

    As seen here:

    R = hexToR("#FFFFFF");
    G = hexToG("#FFFFFF");
    B = hexToB("#FFFFFF");
    
    function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
    function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
    function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
    function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
    

    This script basically takes each color pair from your hexcolor code (for example #F0556A) and switches it to a integer using parseInt with base 16 .

提交回复
热议问题