我可以强制jQuery.css("backgroundColor")以十六进制格式返回吗?

47 rgb jquery hex background-color

我有这样一个元素:

<p>My text with a <strong class="highlighted">sample highlight</strong>.<p>
Run Code Online (Sandbox Code Playgroud)

CSS类就像这样:

.highlighted {
    background: #f0ff05;
    font-weight: normal;
}
Run Code Online (Sandbox Code Playgroud)

但是当我使用这样的jQuery时:

$(".highlighted").css("backgroundColor");
Run Code Online (Sandbox Code Playgroud)

它回来了rgb(240, 255, 5).我可以编写一些函数来从rgb转换为十六进制,但我想知道是否有一些方法让jQuery返回十六进制格式的值.

Eri*_*lli 73

颜色总是以rgb形式返回(除了已经以十六进制返回的IE6 ),然后我们不能以原生的其他格式返回.

就像你说的,你可以编写一个函数来将hex转换为rgb.这是一个主题,有几个如何编写这个函数的例子:如何获得十六进制颜色值而不是RGB值?.

但是你想知道是否有一种方法可以直接返回jQuery中的jQuery:答案是肯定的,这可以使用CSS Hooks,因为jQuery 1.4.3.

代码应该是:

$.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]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当你打电话时$(".highlighted").css("backgroundColor"),回报将是#f0ff05.这是一个工作样本,你看它是否有效.

  • 为了在IE8中实现这种兼容性,将`var bg = elem.currentStyle ["background-color"]更改为``var bg = elem.currentStyle ["backgroundColor"];` (4认同)