In JavaScript, you can use the style object attribute to set the gradient color. The syntax format is "element object.style.backgroundImage='linear-gradient(angle, color, color)'"; the Style object represents a separate Style declaration.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In fact, the implementation of gradient is ultimately controlled by css (style)
All codes are written directly in JS:
var test = document.getelementById(''test); test .style.backgroundImage='linear-gradient(120deg, #155799, #159957)';
PS: The 'i' of the backgroundImage here must be It should be capitalized, and it must be written like this. It cannot be written the same as the background-image in CSS, which will not be recognized by JS.
Extended information:
After writing it in css, add a class to the element through js to add a new style:
Defined in the style sheet Style
css:
.jianbian{ background-image: linear-gradient(120deg, #155799, #159957); }
Then add class to the element through js
js:
var test = document.getelementById(''test); test.className = 'jianbian' ;
That’s it, but you still need to consider the differences Browser compatibility, how to write gradients.
-webket-/-moz-like
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to set gradient color in javascript. For more information, please follow other related articles on the PHP Chinese website!