Introduction to several ways JavaScript can access CSS properties

  • 2020-03-30 03:33:03
  • OfStack

There are generally two ways in which JavaScript can access CSS properties: "access via elements" and "direct access to style sheets." In addition, there is a problem that cannot be ignored when accessing styles -- runtime styles.

1. Access through the element

Since you are accessing the stylesheet through elements, you should first determine which element. This is the content of the DOM, and I won't go into it here. After you get the reference, you can access a property by referencing. Style. The property you want to access. For example, look at the following code.


<pre name="code" class="html"><pre name="code" class="html"><!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<style> 
#a{ 
height:100px; 
width:100px; 
background-color:red; 
} 
</style> 
</head> 
<body> 
<div id="a"></div> 
</body> 
</html>

Document.getelementbyid ("a").style.backgroundcolor; That completes the access, and then whether you want to return or change the property value is up to you.

2. Direct access to style sheets

Direct access to a stylesheet is basically "find the corresponding style block, then find the corresponding style rule in that style block, and finally find the corresponding style in that style rule."

Let's start with style blocks. In code, CSS code will exist in < Style> < / style> Tags between or < Link> Among them, one < Style> < / style> Or < Link> It's just a style block. There may be multiple code blocks arranged from top to bottom in the code, and we can access the style blocks as if they were array elements. For example, if we want to access the first one in the style block, we can document.stylesheets [0]

Then say what style rules are. Let's look at the following code


<pre name="code" class="html"><!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<style> 
#a{ 
height:100px; 
width:100px; 
background-color:red; 
} 
#b{ 
height:100px; 
width:100px; 
background-color:blue; 
} 
</style> 
</head> 
<body> 
<div id="a"></div> 
<div id="b"></div> 
</body> 
</html>

Then we can access the corresponding style. For example, if we want to change the backgroundColor of #b to green, document.stylesheets [0]. CssRules [1]. Style. BackgroundColor ="green";

3. Runtime style

Look at the following code:


<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<style> 
#a{ 
height:100px; 
width:100px; 
color:red; 
} 
#b{ 
height:100px; 
width:100px; 
} 
</style> 
</head> 
<body> 
<div id="a"> 
<div id="b"> Look at the font color </div> 
</div> 
</body> 
</html>

Related articles: