Home  >  Article  >  Web Front-end  >  How to add style in javascript

How to add style in javascript

藏色散人
藏色散人Original
2021-07-03 09:19:0311242browse

How to add styles in javascript: 1. Through the "document.getElementById("box");" method; 2. Through the "head.style.cssText="..."" method; 3. Using setProperty method.

How to add style in javascript

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: b390322fe69e754cc2d7247050226b6d16b28748ea4df4d9c2150843fecfba68 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn