JavaScript access to CSS properties in general there are two kinds: "Access through elements", "direct access style sheet." In addition, there is an issue that cannot be ignored when accessing styles--run-time styles.
1. Access through elements
Now that you want to access the stylesheet through the elements, you should first determine which element it is. This is the content of the DOM, not to say much at first. After you get the reference, you can access a property by referring to. Style. properties to access. For example, look at the following code.
<pre name= "code" class= "HTML" ><pre name= "code" class= "HTML" ><! DOCTYPE html>
We can document.getElementById ("a") when we want to get the background color of the #a. Style.backgroundcolor; This completes the access and then returns or changes the property value. That's all you need.
2. Direct access to style sheets
The direct access style sheet is generally "find the appropriate style block, then find the appropriate style rule in the style block, and finally find the appropriate style in the style rule."
Let's say what is a style block. In code, CSS code exists between <style></style> tags or <link>, and a <style></style> or <link> is a style block. There are multiple blocks of code that can be arranged from top to bottom in code, and we can access the style blocks as we would access the array elements. For example, to access the first of the style blocks, we can document.stylesheets[0]
Then say what is the style rule. First look at the following code
<pre name= "code" class= "HTML" ><! DOCTYPE html>
The #a and #b styles are defined separately in the code, and the collection of the #a的样式的集合或 #b is a style rule. In this style block, the #a is the first style rule, and the second style rule for #b. We can also access style rules like array elements. For example, we would like to access the #b style rules, we can document.stylesheets[0].cssrules[1] of course you can choose to write document.stylesheet[0].rules[1] but this type of writing is not supported by Firefox.
Then we have access to the appropriate style. For example, we want to change the background color of #b to green, you can document.stylesheets[0].cssrules[1].style.backgroundcolor= "green";
3. Run-time style
Look at the following code:
When we run alert (document.getElementById ("B"). Style.color), there is no output on the window, but the font color of the page is clearly red, why? This is because the style object properties of each element are not updated immediately. We need to use the Run-time style when we want to export red on the window. window.getComputedStyle (document.getElementById ("B"), null). Color so that you can access to "red." There is another way to access the Run-time style document.getElementById ("B"). Currentstyle.color but this type of writing is only IE supported.