[英]Adding CSS Gradient as Background Image Programatically
為什么我可以像這樣在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>
我目前正在使用以下版本:
只需刪除;
從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不需要分號來組織樣式屬性(它也不是值的一部分)。 因此,最后,您將擁有:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.