How to get hex color value rather than RGB value?

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

    This one looks a bit nicer:

    var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
    var r   = parseInt(rgb[0], 10);
    var g   = parseInt(rgb[1], 10);
    var b   = parseInt(rgb[2], 10);
    var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);
    

    a more succinct one-liner:

    var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
    var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);
    

    forcing jQuery to always return hex:

    $.cssHooks.backgroundColor = {
        get: function(elem) {
            if (elem.currentStyle)
                var bg = elem.currentStyle["backgroundColor"];
            else if (window.getComputedStyle) {
                var bg = document.defaultView.getComputedStyle(elem,
                    null).getPropertyValue("background-color");
            }
            if (bg.search("rgb") == -1) {
                return bg;
            } else {
                bg = bg.match(/\d+/g);
                function hex(x) {
                    return ("0" + parseInt(x).toString(16)).slice(-2);
                }
                return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
            }
        }
    }
    

提交回复
热议问题