您正在设置并重新设置background
JavaScript 对象的属性一次又一次。
最后,如果您尝试记录要传递给的对象.css()
,你会看到它只包含 2 个属性:最后一个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 )"
});
这段代码当然效率不高。对于理解多个声明的浏览器,它将毫无意义地覆盖那些已经起作用的声明。因此,请根据您认为合适的方式进行优化。