通过程序添加CSS渐变作为背景图像

Adding CSS Gradient as Background Image Programatically

本文关键字:背景 图像 渐变 CSS 过程 程序 添加      更新时间:2024-04-25

为什么我可以在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>

我目前正在运行以下版本:

  • Firefox 45.0.1
  • 铬49.0.2623.110
  • 即11.0.9600.18230

只需从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%);

所以,最终,你会得到:

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 {
  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%);
}
<h1>
CSS Styling
</h1>
<div class="red">
</div>
<h1>
Programmatic Styling
</h1>
<div id="red">
</div>

您可以使用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>