Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从样式属性替换所有RGB_Javascript_Jquery_Regex - Fatal编程技术网

Javascript 从样式属性替换所有RGB

Javascript 从样式属性替换所有RGB,javascript,jquery,regex,Javascript,Jquery,Regex,我需要将所有RGB转换为十六进制 首先,我过滤所有元素以查找具有style属性的元素 wrapper.find('*[style]').filter(function(){ console.log($(this).attr('style'); }); 如果有任何RGB颜色,我需要转换成十六进制 function rgbToHex(rgb){ rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); if (rgb == n

我需要将所有RGB转换为十六进制

首先,我过滤所有元素以查找具有style属性的元素

wrapper.find('*[style]').filter(function(){
    console.log($(this).attr('style');
});
如果有任何RGB颜色,我需要转换成十六进制

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')

样式输出示例:
字体系列:Arial;背景:rgb(255,0,0);线高:10px;颜色:#fff;右边框颜色:rgba(34,64,32,0.5)

如何过滤整个样式以仅获取rgb,转换为十六进制以存储具有新值的输出?

我的答案:

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);
});

你为什么这么做?把它放回去没有什么意义。我没有放回去,我得到的是所有的css,用十六进制替换,然后保存到json中以后使用。所以读出样式并获得一个reg exp来匹配模式,然后替换它。正则表达式是个问题:(不知道怎么做,直到现在都没有尝试过