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

后端 未结 7 480
猫巷女王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:12

    You would do something like:

    $.fn.ToRgb = function()
    {
        if(this.charAt(0) == "#"){this = this.substring(1,7);} //remove the #
        return {
            R : parseInt(this.substring(0,2) ,16),
            G : parseInt(this.substring(2,4) ,16),
            B : parseInt(this.substring(4,6) ,16),
        }
    }
    
    RGB = $('#my_element').css('backgroundColor').ToRgb();
    
    
    /*
       * console.log(rgb) =>
       * {
       *   R: X
       *   G: X
       *   B: X 
       * }
    */
    

    Pretty simple :)

提交回复
热议问题