web-dev-qa-db-fra.com

Puis-je forcer les retours jQuery.css ("backgroundColor") au format hexadécimal?

J'ai un élément comme ça:

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

Et la classe CSS comme ceci:

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

Mais quand j'utilise un jQuery comme celui-ci:

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

Il renvoie rgb(240, 255, 5). Je pourrais écrire une fonction pour convertir de rgb à hex, mais je voudrais savoir s'il existe un moyen pour jQuery de renvoyer la valeur déjà au format hexadécimal.

47
user776290

Les couleurs sont toujours renvoyées comme rgb (sauf IE6 qui retourne déjà en hex), alors nous ne pouvons pas retourner dans un autre format nativement.

Comme vous l'avez dit, vous pouvez écrire une fonction dans convertir hex en rgb. Voici un sujet avec plusieurs exemples d'écriture de cette fonction: Comment obtenir une valeur de couleur hexadécimale plutôt qu'une valeur RVB? .

Mais vous vous demandez s'il existe un moyen de retourner directement le jQuery déjà en hex: la réponse est oui , cela est possible en utilisant CSS Hooks depuis jQuery 1.4.3.

Le code doit être:

$.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]);
        }
    }
}

Et lorsque vous appelez $(".highlighted").css("backgroundColor"), le retour sera #f0ff05. Voici un échantillon de travail pour que vous le voyiez fonctionner.

73
Erick Petrucelli

Ceci est une version légèrement ajustée de la réponse d'Erick Petrucelli. Il semble gérer 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]);
                    }
                }
            }
        };
2
li3