在jQuery中为背景渐变设置-os-/-ms前缀失败



我在这里看到了其他几篇关于jQuery .css()不能与-webkit-gradient一起使用的帖子,但我还没有找到一篇关于-ms-linear-gradient-o-linear-gradientlinear-gradient的帖子。

长话短说,我创建了一个函数,它使用所有最流行的CSS属性为元素设置基于#hex的背景梯度,以实现跨浏览器兼容性,直接取自ColorZilla。

下面是我所说的特定片段:

$(elem).css({
        'background': b,
        'background': '-moz-linear-gradient(top,  '+a+' 0%, '+b+' 100%)', 
        'background': '-webkit-gradient(linear, left top, left bottom, color-stop(0%,'+a+'), color-stop(100%,'+b+'))',
        'background': '-webkit-linear-gradient(top,  '+a+' 0%,'+b+' 100%)',
        'background': '-o-linear-gradient(top,  '+a+' 0%,'+b+' 100%)', // Breaks execution
        'background': '-ms-linear-gradient(top,  '+a+' 0%,'+b+' 100%)', // Breaks execution
        'background': 'linear-gradient(top,  '+a+' 0%,'+b+' 100%)', // Breaks execution
        'filter': 'progid:DXImageTransform.Microsoft.gradient( startColorstr=''+a+'', endColorstr=''+b+'',GradientType=0 )'
        });

我在每个属性旁边放置了一个//breaks execution注释,当这些属性处于活动状态时(集体或单独)会中断脚本的执行(没有设置其他属性,例如background: bb当然是一个变量)。

我完全不明白为什么会这样。

到目前为止,我已经尝试过:

  • 使用双引号而不是单引号
  • 用实际十六进制替换变量用法(+a++b+

我在想,也许这三个角色中有一个需要逃跑或其他什么?

如果有任何帮助来弄清楚为什么会这样,我们将不胜感激!

您正在一次又一次地设置和重新设置JavaScript对象的background属性。

最后,如果您尝试记录要传递给.css()的对象,您会看到它只包含两个属性:列表中的最后一个background值和filter

所以你的代码相当于:

$(elem).css({
    'background': 'linear-gradient(top,  '+a+' 0%,'+b+' 100%)',
    'filter': 'progid:DXImageTransform.Microsoft.gradient( startColorstr=''+a+'', endColorstr=''+b+'',GradientType=0 )'
});

你可以试试这样的东西(jsfiddle演示):

var i, l, backgrounds = [
    '-moz-linear-gradient(top,  '+a+' 0%, '+b+' 100%)', 
    '-webkit-gradient(linear, left top, left bottom, color-stop(0%,'+a+'), color-stop(100%,'+b+'))',
    '-webkit-linear-gradient(top,  '+a+' 0%,'+b+' 100%)',
    '-o-linear-gradient(top,  '+a+' 0%,'+b+' 100%)',
    '-ms-linear-gradient(top,  '+a+' 0%,'+b+' 100%)',
    'linear-gradient(top,  '+a+' 0%,'+b+' 100%)'
];
// Try each background declaration, one at a time
// Like in a stylesheet, the browser should(!) ignore those
// it doesn't understand.
for( i = 0, l = backgrounds.length ; i < l ; i++ ) {
    $(elem).css({ background: backgrounds[i] });
}
$(elem).css({
    'filter': "progid:DXImageTransform.Microsoft.gradient( startColorstr='"+a+"', endColorstr='"+b+"',GradientType=0 )"
});

这个代码当然一点也不高效。对于理解多个声明的浏览器,它将毫无意义地覆盖那些已经工作的声明。因此,根据您的喜好进行优化。