To access the style sheet through elements, you should first determine which element is used. Directly access the style sheet to find the corresponding style rules in the style block, and finally find the corresponding style in the style rule JavaScript access CSS attributes in two ways: "Access through elements" and "Access style sheets directly ". In addition, there is a problem that cannot be ignored when accessing styles-runtime styles.
1. Access through elements
Since you want to access the style sheet through elements, you should first determine which element is used. This is the content of DOM. After obtaining the reference, you can use "reference. style. attribute to be accessed" to access a property. For example, see the following code.
When we want to obtain the background color of # a, we can document. getElementById (""). style. backgroundColor; in this way, the access is completed. If you want to return the result or change the attribute value, you can use it.
2. directly access the style sheet
Directly accessing the style sheet is generally "first find the corresponding style block, then find the corresponding style rules in the style block, and finally find the corresponding style in the style rule ".
First, let's talk about the style block. In the code, the CSS code will exist inBetween tags or
OneOr
Is a style block. Multiple code blocks may be arranged from top to bottom in the code. We can access the style blocks just like accessing array elements. For example, to access the first style block, you can use document. styleSheets [0].
Then, let's talk about the style rules. First look at the following code
The Code specifies the # a and # B styles. The # a style set or # B set is a style rule. In this style block, # a is the first style rule, and # B is the second style rule. We can also access style rules like accessing array elements. For example, if you want to modify the rule B, you can use document.stylesheets1_02.16.css Rules [1]. Of course, you can choose to write document. styleSheet [0]. rules [1], but this method is not supported by Firefox.
Then we can access the corresponding style. For example, to change the background color of ingress B to green, you can use document.stylesheets1_02.16.css Rules [1]. style. backgroundColor = "green ";
3. runtime Style
See the following code:
Observe font color
When we run alert (document. getElementById ("B"). style. color);, we find that nothing is output in the pop-up window, but the font color of the page is obviously red. Why? This is because the style object attributes of each element are not updated in real time. We need to use the runtime style when we want to output the red color in a pop-up window. Window. getComputedStyle (document. getElementById ("B"), null). color to access "red ". There is also another way to write document. getElementById ("B"). currentStyle. color when accessing the runtime style, but this method is only supported by IE.