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

How to set css in javascript

藏色散人
Release: 2023-01-05 16:12:40
Original
8289 people have browsed it

How to set css in javascript: 1. Set the style object directly through inline style; 2. Set the style attribute by adding global style; 3. Use JavaScript to add and delete classes "add()" and "remove( )" set css.

How to set css in javascript

The operating environment of this article: windows7 system, javascript1.8.5&&HTML5&&CSS3 version, Dell G3 computer.

javascript sets css style

1. Directly set the style object (inline style)

The easiest way to set the element style using JavaScript is to use style attribute. There is a style object for every HTML element we access through JavaScript. This object allows us to specify CSS properties and set their values. For example, this is the style to set the font color, background color, and style of the HTML element with the id value demo:

var myElement = document.querySelector("#demo");
// 把颜色设置成紫色
elem.style.color = 'purple';  
// 将背景颜色设置为浅灰色
elem.style.backgroundColor = '#e5e5e5';  
// 将高度设置为150 px
elem.style.height = '150px';
Copy after login

Note: JavaScript uses the camel case principle (for example: backgroundColor) instead of dash (background-color) Represents the attribute name

The style attribute adds a style inline on the element:

<div id="demo" style="color: purple; background-color: #e5e5e5; height: 150px;">     
     Hello, world! 
</div>
Copy after login

However, this can make our markup very confusing. Browser rendering performance is also poor.

2. Set the style attribute--add a global style

Another method is to inject elements with CSS attributes in into the DOM. This is useful when setting styles that apply to a group of elements rather than just one.

First, we will create a style element.

var style = document.createElement(&#39;style&#39;);
Copy after login

Next, we will add our style to