How to convert “background-color” to rgb() format?

前端 未结 3 1178
無奈伤痛
無奈伤痛 2021-02-19 22:47

Here is my problem:

I want to change the opacity of background-color of one of the elements on my page. in order to do this I need to first convert the color to rgb() fo

3条回答
  •  不要未来只要你来
    2021-02-19 23:16

    This function will get you the r and g and b that you can use to create any format you want:

    color_1 = resolve_color('#FFCC00');
    
    color_2 = resolve_color('#FC0');
    
    color_3 = resolve_color('rgb(255, 204, 0)');
    
    color_4 = resolve_color('rgb(100%, 80%, 0%)');
    

    In all examples, color_N is:

    /* color_N is an array
     *   - color_N['red']    : 255
     *   - color_N['greenn'] : 204
     *   - color_N['red']    : 0
     */
    

    Function

    function resolve_color(color){
        // return an array containing R, G and B values
        if(color === 'transparent')// IE (6 and ?)
            color = '#FFF';
        var r,g,b;
        var hex_color_pcre = new RegExp("^#[0-9a-f]{3}([0-9a-f]{3})?$",'gi');
        var rgb_color_pcre = new RegExp("rgb\\(\\s*((?:[0-2]?[0-9])?[0-9])\\s*,\\s*((?:[0-2]?[0-9])?[0-9])\\s*,\\s*((?:[0-2]?[0-9])?[0-9])\\s*\\)$",'gi');
        var rgb_percent_color_pcre = new RegExp("rgb\\(\\s*((?:[0-1]?[0-9])?[0-9])%\\s*,\\s*((?:[0-1]?[0-9])?[0-9])%\\s*,\\s*((?:[0-1]?[0-9])?[0-9])%\\s*\\)$",'gi');
        if(color.match(hex_color_pcre)){
            if(color.length == 4){
                r  = color.charAt(1)+""+color.charAt(1);
                g  = color.charAt(2)+""+color.charAt(2);
                b  = color.charAt(3)+""+color.charAt(3);
            }
            else{
                r  = color.charAt(1)+""+color.charAt(2);
                g  = color.charAt(3)+""+color.charAt(4);
                b  = color.charAt(5)+""+color.charAt(6);
            }
            r = h2d(r);
            g = h2d(g);
            b = h2d(b);
        }
        else if(color.match(rgb_color_pcre)){
            r = RegExp.$1;
            g = RegExp.$2;
            b = RegExp.$3;
        }
        else if(color.match(rgb_percent_color_pcre)){
            r = parseInt((RegExp.$1)*2.55);
            g = parseInt((RegExp.$2)*2.55);
            b = parseInt((RegExp.$3)*2.55);
        }
        else
            return false;
    
        var returned =[];
        returned['red'] = r;
        returned['green'] = g;
        returned['blue'] = b;
        return returned;
    }
    
    function h2d(h) {
        // hex to decimal
        return parseInt(h,16);
    } 
    

    source: http://www.kadimi.com/en/javascript-tween-function-368

提交回复
热议问题