Document. stylesheets can obtain a set of style sheets, because the browsers are very different, and the rules for accessing style sheets are also different. dom specifies a cssrules set for each style sheet. Mozilla and Safari correctly implement this standard, but it is a pity that IE defines this set as rules, therefore, you can use the following code to obtain the correct object:
VaR ocssrules?document.stylesheets=02.16.css rules | document. stylesheets [0]. Rules;
In this way, the CSS set of different browsers can be obtained.
Use the following JS Code to obtain the style in the style sheet:
The Code is as follows:
Function getcss ()
{
VaR ocssrules?document.stylesheets=02.16.css rules | document. stylesheets [0]. Rules;
Alert (ocssrules [0]. style. backgroundcolor );
}
Stylesheets [0] indicates the first style table reference, ocssrules [0] indicates the first style rule (that is, the content of # Main {}), and uses the style attribute to access specific rules.
Similarly, the Code for changing the style sheet rule is as follows:
The Code is as follows:
Function setcss ()
{
VaR ocssrules?document.stylesheets=02.16.css rules | document. stylesheets [0]. Rules;
Ocssrules [0]. style. backgroundcolor = "red ";
Ocssrules [0]. style. marginleft = "20px ";
Ocssrules [0]. style. margintop = "20px ";
}
However, it should be noted that many elements may be associated with the same style sheet, so be careful when changing the style sheet.
In addition to the style object and CSS rules of the element, each element also has a final style that tells us how the element is finally displayed on the screen, that is, the style after overlapping Calculation of style and CSS. IE and Dom can access this style in two ways. ie uses the currentstyle attribute, and Dom uses the getcomputedstyle () method.
The method for js to obtain the final style is as follows:
The Code is as follows:
Function getfinalcss ()
{
VaR odiv = Document. getelementbyid ("Main ");
// Access the style attribute
Alert (odiv. style. backgroundcolor );
// IE Method
Alert (odiv. currentstyle. backgroundcolor );
// DOM method. The second parameter is a pseudo element, such as hover and first-leeter.
// Alert (document. defaultview. getcomputestyle (odiv, null). backgroundcolor );
}
It should be noted that currentstyle is a read-only attribute and cannot be assigned a value to it, because it is a style rule after multiple styles are integrated, which is not difficult to understand.
For the getcomputedstyle method, you can call it through document. defaultview (ie and Safari do not support this method). Therefore, when using the getcomputedstyle method, it is best to test it in multiple browsers.
Window. getcomputedstyle? Window. getcomputedstyle (ID, null ). backgroundcolor: ID. currentstyle ["backgroundcolor"]; if it is used to obtain the background color, the return value in Firefox and IE is still different. In ie, the return value is "# ffff99, in Firefox, "# ee2c22" is returned"