使用相同属性的JavaScript添加多行CSS

时间:2013-09-27 13:31:03

标签: javascript css

我正在尝试为同一属性添加多行CSS(多个浏览器的覆盖),但我只看到最后一个附加。

我知道为什么会发生这种情况,但我不知道如何解决这个问题。将=更改为+=也无效。我应该如何更改它以便正确附加它们?

    ribbon.style.background = '-webkit-linear-gradient(left, ' + config.ribbonColorStart + ' 0%, ' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = '-moz-linear-gradient(left, ' + config.ribbonColorStart + ' 0%, ' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = '-o-linear-gradient(left, ' + config.ribbonColorStart + ' 0%,' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = '-ms-linear-gradient(left, ' + config.ribbonColorStart + ' 0%,' + config.ribbonColorEnd + ' 100%)';
    ribbon.style.background = 'linear-gradient(to right, ' + config.ribbonColorStart + ' 0%,' + config.ribbonColorEnd + ' 100%)';

1 个答案:

答案 0 :(得分:1)

你必须浏览器检测它。类似的东西:

try {
  ribbon.style.backgroundImage = "linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    ribbon.style.backgroundImage = "-webkit-linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    ribbon.style.backgroundImage = "-moz-linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    ribbon.style.backgroundImage = "-o-linear-gradient(...)";
  if( !ribbon.style.backgroundImage || ribbon.style.backgroundImage == "none")
    // gradient not supported, fall back here
}
catch(e) {
  // gradient not supported and browser does't like bad values. Fall back here
}

应该注意-ms-linear-gradient从未存在过:IE9不支持渐变,IE10完全支持它们。

当然,您可以将样式放在类中,并将该类添加到元素中;)