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

Two ways to change css style in native js

迷茫
Release: 2017-03-26 16:58:47
Original
1741 people have browsed it

Below I will introduce to you two ways to change CSS styles in native js:

1Through the node in the javascript code. style.cssText="css expression 1; css expression 2; css expression 3 " directly changes the CSS style.

2First set the style for a specific class such as the "active class" in the CSS style sheet (the active class here is assumed and does not exist for the time being), and then in the javascript code Through node.classname="active", the style setting of the active class in the CSS style sheet is attached to the node node.

The following is a detailed introduction, first is the html code:

<style type="text/css">
           p {
			float: left;
			padding: 20px;
			margin: 10px;
			border: 1px solid #000;
			background-color: #fff;
			color: #000;
		}
           .active
                {
                       background-color:blue
                }
</style>
<body>
      <p class="root">
      </p>
</body>
Copy after login

is just a simple p, the running result is

First use the above The first way to change the css style is to write the following javascript code:

<script type="text/javascript">  
  var root=document.getElementsByClassName("root")[0];
  root.style.cssText="background-color: blue;color: #fff;";
</script>
Copy after login

The running result is:

Then use the second method mentioned above To change the css style, write the following javascript code:

<script type="text/javascript">  
    var root=document.getElementsByClassName("root")[0];
    root.className="active";
</script>
Copy after login

The same running result is:

Summary: The results of these two methods are the same, but As far as the operation process is concerned, the second method, which is the "node.classname" method, separates the writing of css and js, which is obviously more reasonable and orderly. If the css statement is relatively simple, there is no difference between the two methods, but if the css statement is relatively complex, obviously the second method is more methodical.

The above is the detailed content of Two ways to change css style in native js. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!