设置-os – / – jQuery中背景渐变的ms前缀无法正常工作?
我在这里看到了几个关于jQuery .css()
的其他post没有使用-webkit-gradient
,但是我还没有找到一个关于-ms-linear-gradient
, -o-linear-gradient
post和linear-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: b
( b
当然是变量))。
我完全不知道为什么会这样。
到目前为止,我已经尝试过:
- 使用双引号而不是单引号。
- 用实际的hex替换变量用法(
+a+
,+b+
)。
我想也许这三个人中有一个角色需要逃脱或者什么?
任何帮助,以弄清楚为什么这将是非常感谢!
您是一次又一次地设置和重新设置JavaScript对象的background
属性。
最后,如果您尝试记录传递给.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 demo ):
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 )" });
这段代码当然不是很有效。 对于理解多个声明的浏览器,它将毫无意义地覆盖那些已经工作的浏览器。 因此,根据您的需要进行优化。