How to dynamically change a CSS stylesheet with JavaScript

不言
Release: 2018-12-05 09:45:47
Original
2758 people have browsed it

How to dynamically change CSS classes (style sheets) with JavaScript? To change a class name in JavaScript, you need to change the element's className attribute. This article will introduce the code to dynamically change CSS (style sheet) classes using JavaScript.

How to dynamically change a CSS stylesheet with JavaScript

Let’s look directly at an example

Create the following HTML file.

JavaScriptChangeCssClass.html

     

这篇文章是很重要的,需要特别注意。

Copy after login

JavaScriptChangeCssClass.css

.importantText{ font-weight:700; color:#FF0000; }
Copy after login

Description:

Click the button and the following code part will be executed

function buttonClick() { target = document.getElementById("important"); if (target != null) { target.className = "importantText"; } }
Copy after login
target = document.getElementById("important");
Copy after login

Therefore, the ID gets the important element. In this case, you can get the element with "important".

if (target != null) { target.className = "importantText"; }
Copy after login

If the element can be obtained, it is a non-null value, so the inner part of the if statement is executed. You can set the class of an element by assigning the className attribute. In this example, "importantText" is set to the class name.

According to this processing

重要
Copy after login

changed the status.

Running results

Use a web browser to display the above HTML file. The effect shown below will be displayed.

How to dynamically change a CSS stylesheet with JavaScript

Click the "button" button, the following effect will be displayed, "Important" will become a red font

How to dynamically change a CSS stylesheet with JavaScript

The above is the entire content of this article. For more related exciting content, you can go to theJavaScript Video Tutorialcolumn on the php Chinese website for further learning! ! !

The above is the detailed content of How to dynamically change a CSS stylesheet with 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!