繁体   English   中英

jQuery将CSS颜色设置为HEX而不是RGB

[英]jQuery set CSS color as HEX instead of RGB

我正在尝试创建一个jQuery挂钩,该挂钩将读取所有颜色并将其设置为十六进制值而不是RGB。 我发现了一个可以正确将颜色读取为十六进制的钩子,但是我不确定如何修改它以将CSS颜色写入十六进制。

因此,例如,我想要$(“ h1”)。css('color','#333333'); 可以使用“ style ='color:#333333;'”(而不是当前的RGB等价)来内联样式h1。 我用来返回十六进制读取颜色的钩子是:

$.cssHooks.color = {
get: function(elem) {
    if (elem.currentStyle)
        var bg = elem.currentStyle["color"];
    else if (window.getComputedStyle)
        var bg = document.defaultView.getComputedStyle(elem,
            null).getPropertyValue("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]);
    }
}}

更新

通过将所有元素样式都转换为十六进制,然后重建样式并通过$(elm).attr(style,styles)进行设置,我能够以超级回旋的方式完成此操作。 似乎很hacky和令人费解,但它可以工作。

该方法似乎对我有用,但是它假定格式正确的字符串。 您可以将检查添加到此功能:

function rgb_to_hex(rgb_color) {
    if (!rgb_color) return ''
    return rgb_color
        .replace(/.*rgba?\(([^(]+)\).*/gi, '$1')
        .split(',')
        .splice(0,3)
        .reduce(function(acc, cur) { return acc+format_hex(cur) }, '');
}

function format_hex(ns) {
    var v;
    return isNaN(v = parseInt(ns)) ? '' : ('00' + v.toString(16)).substr(-2);
}

var v,
    color1 = (v = rgb_to_hex('rgb(0,0,0)')) !== '' ?  '#' + v : '',
    color2 = (v = rgb_to_hex('rgb(0,255,0)')) !== '' ?  '#' + v : '',
    color3 = (v = rgb_to_hex('rgba(123,39,12, .1)')) !== '' ?  '#' + v : '',
    color4 = (v = rgb_to_hex()) !== '' ?  '#' + v : '';
    color5 = (v = rgb_to_hex('gobbledegook')) !== '' ?  '#' + v : '';
console.log(color1); // '#000000'
console.log(color2); // '#00ff00'
console.log(color3); // '#7b270c'
console.log(color4); // ''
console.log(color5); // ''

另外,此部分:

if (elem.currentStyle)
    var bg = elem.currentStyle["color"];
else if (window.getComputedStyle)
    var bg = document.defaultView.getComputedStyle(elem, null)
        .getPropertyValue("color");

应该是这样的:

var bg = '';
if (elem.currentStyle) {
    bg = elem.currentStyle["color"];
} else if (window.getComputedStyle) {
    bg = document.defaultView.getComputedStyle(elem, null)
        .getPropertyValue("color");
}

因为可能未定义bg

您遇到的问题是jQuery不会写您想要的东西,但会写出它能理解的东西。 您可以像这样“强制”代码执行所需的操作:

$('h1').css('color', '');
$('h1').attr('style', $('h1').attr('style') + 'color: #FFEE02');

您必须使用第一行才能使html代码不会增长太多,而在第二行中,请在html上设置颜色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM