【问题标题】:Can I force jQuery.css("backgroundColor") returns on hexadecimal format?我可以强制 jQuery.css("backgroundColor") 以十六进制格式返回吗?
【发布时间】:2011-09-04 20:50:23
【问题描述】:

我有一个这样的元素:

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

CSS 类是这样的:

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

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

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

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

【问题讨论】:

  • 不。没有用于执行此操作的 jquery 方法或属性。开始编写自己的代码。看看这里,stackoverflow.com/questions/1740700/…
  • 为什么需要十六进制? rgb 不是更容易解析吗?
  • 我将使用 AJAX 发送十六进制值,并且服务器端代码(我无法更改)期望使用十六进制。

标签: jquery rgb hex background-color


【解决方案1】:

颜色总是以 rgb 的形式返回(IE6 除外,它已经以 hex 的形式返回),那么我们不能原生地以另一种格式返回。

如您所说,您可以编写一个函数来将十六进制转换为 rgb。这里有几个例子说明如何编写这个函数:How to get hex color value rather than RGB value?

但是你想知道是否有办法直接返回十六进制的 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]);
        }
    }
}

当您调用$(".highlighted").css("backgroundColor") 时,返回将是#f0ff05。这是working sample,您可以看到它的工作原理。

【讨论】:

  • 但是你的代码只有get。我可以使用$(".highlight").css("backgroundColor", "#ff0000") 了吗?
  • 由于我们没有覆盖设置器,因此您可以继续工作而无需更改。我的工作示例有一个示例。
  • 酷,我在示例中没有看到这个。谢谢!
  • 我不确定这是否只是我正在测试的机器,但 IE8 尝试使用此 shim 时抛出异常。它在if (bg.search("rgb") == -1) 行上为 bg 抛出一个未定义的错误,这意味着 bg 不是从第一个 if else 语句中定义的。需要注意的是,我只是在实际版本的 IE8 上体验到这一点,而不是在 IE9 上使用开发工具模拟 IE8。
  • 为了在 IE8 中兼容,将 var bg = elem.currentStyle["background-color"]; 更改为 var bg = elem.currentStyle["backgroundColor"];
【解决方案2】:

这是 Erick Petrucelli 答案的略微调整版本。它似乎可以处理 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]);
                    }
                }
            }
        };

【讨论】:

    【解决方案3】:
    function RGBAToHexA(test:string) {
    let sep = test.toString().indexOf(",") > -1 ? "," : " ";
    const rgba = test.toString().substring(5).split(")")[0].split(sep);
    console.log(rgba)
    let r = (+rgba[0]).toString(16),
      g = (+rgba[1]).toString(16),
      b = (+rgba[2]).toString(16),
      a = Math.round(+rgba[3] * 255).toString(16);
    
        if (r.length == 1)
            r = "0" + r;
        if (g.length == 1)
            g = "0" + g;
        if (b.length == 1)
            b = "0" + b;
        if (a.length == 1)
            a = "0" + a;
    
    return "#" + r + g + b + a;}
    

    这段代码对我来说很好用,我正在使用 Jasmine 量角器,当我尝试获取元素的 cssValue 时,我得到了 rgb 格式。

    it('should check color  of login btn', async function(){
        browser.waitForAngularEnabled(true);
        browser.actions().mouseMove(element(by.css('.btn-auth, .btn-auth:hover'))).perform(); // mouse hover on button
        csspage.Loc_auth_btn.getCssValue('color').then(function(color){
            console.log(RGBAToHexA(color))
            expect( RGBAToHexA(color)).toContain(cssData.hoverauth.color);
    
        })
       // expect(csspage.Loc_auth_btn.getCssValue('color')).toContain(cssData.hoverauth.color);
    })
    

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2015-04-11
      • 2022-06-22
      相关资源
      最近更新 更多