How to get hex color value rather than RGB value?

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

    0 讨论(0)
  • 2020-11-21 23:29

    Here is the cleaner solution I wrote based on @Matt suggestion:

    function rgb2hex(rgb) {
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
    

    Some browsers already returns colors as hexadecimal (as of Internet Explorer 8 and below). If you need to deal with those cases, just append a condition inside the function, like @gfrobenius suggested:

    function rgb2hex(rgb) {
        if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
    
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
    

    If you're using jQuery and want a more complete approach, you can use CSS Hooks available since jQuery 1.4.3, as I showed when answering this question: Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

    0 讨论(0)
  • 2020-11-21 23:29

    Here is my solution, also does touppercase by the use of an argument and checks for other possible white-spaces and capitalisation in the supplied string.

    var a = "rgb(10, 128, 255)";
    var b = "rgb( 10, 128, 255)";
    var c = "rgb(10, 128, 255 )";
    var d = "rgb ( 10, 128, 255 )";
    var e = "RGB ( 10, 128, 255 )";
    var f = "rgb(10,128,255)";
    var g = "rgb(10, 128,)";
    
    var rgbToHex = (function () {
        var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
    
        function pad(num) {
            if (num.length === 1) {
                num = "0" + num;
            }
    
            return num;
        }
    
        return function (rgb, uppercase) {
            var rxArray = rgb.match(rx),
                hex;
    
            if (rxArray !== null) {
                hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));
    
                if (uppercase === true) {
                    hex = hex.toUpperCase();
                }
    
                return hex;
            }
    
            return;
        };
    }());
    
    console.log(rgbToHex(a));
    console.log(rgbToHex(b, true));
    console.log(rgbToHex(c));
    console.log(rgbToHex(d));
    console.log(rgbToHex(e));
    console.log(rgbToHex(f));
    console.log(rgbToHex(g));
    

    On jsfiddle

    Speed comparison on jsperf

    A further improvement could be to trim() the rgb string

    var rxArray = rgb.trim().match(rx),
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-11-21 23:32

    Try

    // c - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
    let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
    

    // rgb - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
    let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
    
    console.log(rgb2hex("rgb(12,233,43"));

    0 讨论(0)
提交回复
热议问题