Home > Web Front-end > JS Tutorial > body text

How to add style in javascript

藏色散人
Release: 2023-01-07 11:41:52
Original
11254 people have browsed it

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:

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";//设置背景色为灰色
Copy after login

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";
Copy after login

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');
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template