javascript 程序化添加CSS渐变作为背景图像

cnh2zyt3  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(86)

为什么我可以像这样在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
  • IE 11.0.9600.18230
3zwjbxry

3zwjbxry1#

只需从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>
r6vfmomb

r6vfmomb2#

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

相关问题