How to get hex color value rather than RGB value?

前端 未结 19 3152
猫巷女王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:25

    Function that returns background color of an element in hex.

    function getBgColorHex(elem){
        var color = elem.css('background-color')
        var hex;
        if(color.indexOf('#')>-1){
            //for IE
            hex = color;
        } else {
            var rgb = color.match(/\d+/g);
            hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
        }
        return hex;
    }
    

    usage example:

    $('#div1').click(function(){
       alert(getBgColorHex($(this));
    }
    

    jsfiddle

提交回复
热议问题