jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了我可以强制jQuery.css(“backgroundColor”)返回十六进制格式吗?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个这样的元素:
<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转换为十六进制,但我想知道是否有一些方法jQuery返回的值已经十六进制格式。

解决方法

颜色总是返回为rgb(除了已经以十六进制返回的IE6),那么我们不能以其他格式返回。

像你说的,你可以写一个函数来将hex转换为rgb。这里是一个主题,有几个例子如何写这个函数Get hex value rather than RGB value using 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]);
        }
    }
}

当你调用$(“。highlight”)。css(“BACkgroundColor”),返回将是#f0ff05。这里是一个working sample你看到它的工作。

大佬总结

以上是大佬教程为你收集整理的我可以强制jQuery.css(“backgroundColor”)返回十六进制格式吗?全部内容,希望文章能够帮你解决我可以强制jQuery.css(“backgroundColor”)返回十六进制格式吗?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。