Before introducing JS operations on CSS styles, I would like to introduce how CSS styles are loaded in HTML of webpages. Loading CSS styles on HTML pages can be divided into three forms: inline style, internal style sheet, and external style sheet ).
Embedded styles are used to directly add the style attribute to the DOM element to change the table element effect, for example, <Div style = "color: # f00"> embedded styles </div>. It can only change the style of this element.
An internal style adds a CSS style to the page. For example, add <style type = "CSS/text"> Div {color: # f00} </style> to the page. It can change the effect of the entire page element.
External style is used to load an external CSS style file. There are two ways to load external styles: <LINK rel = "stylesheet" type = "text/CSS" href = "test.css"/>, the other is: <style type = "CSS/text"> @ import test.css </style>.
Finally, let's talk about how JS operates CSS styles.
1. js operations embedded style.
<SCRIPT type = "text/JavaScript">
Document. getelementbyid ('test'). style. Color = '#000 ';
</SCRIPT>
2. js operation internal style.
<SCRIPT type = "text/JavaScript">
Method 1:
Function getstyle (selector, ATTR ){ For (I = 0, Len = Document. stylesheets. length; I <Len; I ++ ){ VaR rules; If (document. stylesheets [I]. Rules ){ /* For IE */ Rules = Document. stylesheets [I]. Rules; } Else { /* For non-ie */ Rules = document.stylesheetspolici2.16.css rules; } For (j = 0, rlen = rules. length; j <rlen; j ++ ){ If (rules [J]. selectortext = selector ){ Alert (rules [J]. Style [ATTR]); } } }}
</SCRIPT>
Method 2:
<SCRIPT type = "text/JavaScript">
IE: elementobj. currentstyle
W3C standard: window. getcomputedstyle (Elementobj, null) Or document. defaultview. getcomputedstyle (elementobj, null)
Document. defaultview. getcomputedstyle?Document. defaultview. Getcomputedstyle (ID, null). getpropertyvalue ("background-color"): Id. currentstyle ["backgroundcolor"];
</Scirpt>
3. js operation external style.