How to get hex color value rather than RGB value?

前端 未结 19 3149
猫巷女王i
猫巷女王i 2020-11-21 23:06

Using the following jQuery will get the RGB value of an element\'s background color:

$(\'#selector\').css(\'backgroundColor\');

Is there a

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:30

    Readable && Reg-exp free (no Reg-exp)

    I've created a function that uses readable basic functions and no reg-exps.
    The function accepts color in hex, rgb or rgba CSS format and returns hex representation.
    EDIT: there was a bug with parsing out rgba() format, fixed...

    function getHexColor( color ){
        //if color is already in hex, just return it...
        if( color.indexOf('#') != -1 ) return color;
        
        //leave only "R,G,B" :
        color = color
                    .replace("rgba", "") //must go BEFORE rgb replace
                    .replace("rgb", "")
                    .replace("(", "")
                    .replace(")", "");
        color = color.split(","); // get Array["R","G","B"]
        
        // 0) add leading #
        // 1) add leading zero, so we get 0XY or 0X
        // 2) append leading zero with parsed out int value of R/G/B
        //    converted to HEX string representation
        // 3) slice out 2 last chars (get last 2 chars) => 
        //    => we get XY from 0XY and 0X stays the same
        return  "#"
                + ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
                + ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
                + ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
    }
    

提交回复
热议问题