Can I force jQuery.css(“backgroundColor”) returns

2020-01-24 04:31发布

问题:

I have an element like this:

<p>My text with a <strong class="highlighted">sample highlight</strong>.<p>

And the CSS class like this:

.highlighted {
    background: #f0ff05;
    font-weight: normal;
}

But when I use a jQuery like this:

$(".highlighted").css("backgroundColor");

It returns rgb(240, 255, 5). I could write some function to convert from rgb to hex, but I would like to know if there is some way to jQuery return the value already on hexadecimal format.

回答1:

Colors are always returned as rgb (except IE6 which already returns in hex), then we cannot return in another format natively.

Like you said, you can write a function to convert hex to rgb. Here is a topic with several examples of how to write this function: How to get hex color value rather than RGB value?.

But you wonder if there is a way to directly return the jQuery already in hex: the answer is yes, this is possible using CSS Hooks since jQuery 1.4.3.

The code should be:

$.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(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
        }
    }
}

And when you call $(".highlighted").css("backgroundColor"), the return will be #f0ff05. Here is a working sample to you see it working.



回答2:

This is a slightly adjusted version of Erick Petrucelli's answer. It appears to handle RGBA.

            $.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('rgba') > -1) {
                    return '#00ffffff';
                } else {
                    if (bg.search('rgb') == -1) {
                        return bg;
                    } else {
                        bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
                        function hex(x) {
                            return ("0" + parseInt(x).toString(16)).slice(-2);
                        }
                        return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
                    }
                }
            }
        };