How to get hex color value rather than RGB value?

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

    Since the question was using JQuery, here’s a JQuery plugin based on Daniel Elliott’s code:

    $.fn.cssAsHex = function(colorProp) {
    
        var hexDigits = '0123456789abcdef';
    
        function hex(x) {
            return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
        };
    
        // Convert RGB color to Hex format
        function rgb2hex(rgb) {
            var rgbRegex = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            return '#' + hex(rgbRegex[1]) + hex(rgbRegex[2]) + hex(rgbRegex[3]);
        };
    
        return rgb2hex(this.css(colorProp));
    };
    

    Use it like:

    var hexBackgroundColor = $('#myElement').cssAsHex('background-color');
    

提交回复
热议问题