【问题标题】:Replace all RGB from style attribute替换样式属性中的所有 RGB
【发布时间】:2017-08-30 04:03:44
【问题描述】:

我需要将所有 RGB 转换为 HEX。

首先我过滤所有元素以找到具有样式属性的元素。

wrapper.find('*[style]').filter(function(){
    console.log($(this).attr('style');
});

如果有任何RGB颜色,我需要转换成HEX

function rgbToHex(rgb){
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    if (rgb == null) {
        return "";
    } else {
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
}
function hex(x) {
    var hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
    return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}

要调用的函数是rgbToHex($(this).css('color'));

样式输出示例:font-family:Arial; background:rgb(255, 0, 0); line-height:10px; color:#fff; border-right-color:rgba(34,64,32,0.5);

如何过滤整个样式以仅获取 rgb,转换为十六进制以便能够使用新值存储输出?

【问题讨论】:

  • 你为什么要这样做?将其重新设置没有意义。
  • 我没有退缩,我得到了所有的 css,用 hex 替换而不是保存到 json 中以供以后使用
  • 所以读出样式并获得一个正则表达式来匹配模式,而不是替换它。
  • 正则表达式是问题所在 :( 不知道该怎么做,直到现在都没有运气尝试过

标签: javascript jquery regex


【解决方案1】:

我的回答:

wrapper.find('*[style]').filter(function(){
    var output = '',
        thisStyle = $(this).attr('style'),
        arrayStyle = thisStyle.split(';').filter(function(el) {
            return el.length != 0
        });
    $.each(arrayStyle, function(i,c){
        var replaceRgb = c.replace(/ /g,'');
        if(c.indexOf('rgb') !== -1) {
            c = c.split(':');
            replaceRgb = c[0]+':'+rgbToHex(c[1].replace(/ /g,''));
        }
        output += replaceRgb+';'
    });
    console.log(output);
});

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2015-07-06
    相关资源
    最近更新 更多