以编程方式将CSS渐变添加为背景图像

时间:2016-04-09 23:55:19

标签: javascript css

为什么我可以像这样在CSS中定义规则

.red {
    background-color: red;
    background-image: linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%);
}

并且一切都很好,但是当我在JS中这样做时

var red = document.getElementById('red');
red.style.backgroundColor = 'red';
red.style.backgroundImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%);';

它似乎只适用于IE,而不是Chrome或Firefox?

当需要在JavaScript中设置样式时,如何获得相同的行为?



var red = document.getElementById('red');
red.style.backgroundColor = 'red';
red.style.backgroundImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%);';

div {
  display: inline-block;
  color: white;
  text-align: center;
  text-shadow: 0 1px 5px black;
  font-size: 2em;
  vertical-align: top;
  width: 200px;
  height: 100px;
}
.red {
  background-color: red;
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.01) 1%, rgba(0, 0, 0, 1) 100%);
}

<div class="red">
  CSS Styling
</div>
<div id="red">
  Programmatic Styling
</div>
&#13;
&#13;
&#13;

我目前正在使用以下版本:

  • Firefox 45.0.1
  • Chrome 49.0.2623.110
  • IE 11.0.9600.18230

2 个答案:

答案 0 :(得分:6)

只需从Javascript上的backgroundImage值末尾删除;,当前为:
linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%);

由于Javascript不需要分号来组织样式属性(并且它不是值的一部分)。所以,最后,你将拥有:

&#13;
&#13;
var red = document.getElementById('red');
red.style.backgroundColor = 'red';
red.style.backgroundImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%)';
&#13;
div {
  width: 200px;
  height: 100px;
}
.red {
  background-color: red;
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.01) 1%, rgba(0, 0, 0, 1) 100%);
}
&#13;
<h1>
CSS Styling
</h1>
<div class="red">
</div>
<h1>
Programmatic Styling
</h1>
<div id="red">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用setAttribute来代替:

编辑:哦,或者只是删除字符串中的分号,就像一位评论员建议的那样:

var red = document.getElementById('red');
red.style.backgroundColor = 'red';
red.style.backgroundImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%)';

原始答案内容(忽略或随意使用):

var red = document.getElementById('red');
red.setAttribute('style', 'background-color:red;background-image: linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.01) 1%,rgba(0,0,0,1) 100%)');
div {
  display: inline-block;
  color: white;
  text-align: center;
  text-shadow: 0 1px 5px black;
  font-size: 2em;
  vertical-align: top;
  width: 200px;
  height: 100px;
}
.red {
  background-color: red;
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.01) 1%, rgba(0, 0, 0, 1) 100%);
}
<div class="red">
  CSS Styling
</div>
<div id="red">
  Programmatic Styling
</div>