Home  >  Article  >  Web Front-end  >  How to dynamically change a CSS stylesheet with JavaScript

How to dynamically change a CSS stylesheet with JavaScript

不言
不言Original
2018-11-29 17:54:562689browse

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


    
    
    
    


    

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

JavaScriptChangeCssClass.css

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

Description:

Click the button and the following code part will be executed

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

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

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

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

  重要

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 the JavaScript Video Tutorial column 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!

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