How to add styles in javascript: 1. Through the "document.getElementById("box");" method; 2. Through the "head.style.cssText="..."" method; 3. Using setProperty method.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to add styles in javascript?
js adds css style
The following is a simple case:
We want to add a div with the id of box style. We're going to add width, height, background color to it.Method 1:
var head= document.getElementById("box"); //获取到id为box的div标签元素。 head.style.width = "70px"; //设置宽度为70 head.style.height = "70px";//设置高度为70 head.style.display = "#ccc";//设置背景色为灰色
This method is relatively simple, but if there are many CSS styles, such as margin, padding, font-size, etc., then we still write like this , that would be a lot. At this time, we can use method two.
Method 2:
var head= document.getElementById("box");//获取到id为box的div标签元素。 head.style.cssText="width:70px;height:70px;display:#ccc";
In this method, we use "cssText", so we greatly reduce the code. Just like writing in a CSS source file.
Method 3: Use setProperty
element.style.setProperty('height', '300px', 'important');
If you want to set !important, it is recommended to use this method to set the third parameter
Recommended learning: "javascript Advanced Tutorial 》
The above is the detailed content of How to add style in javascript. For more information, please follow other related articles on the PHP Chinese website!