HTML and CSS Reference
In-Depth Information
where index is the index number of the style rule within the sheet. Thus, the following
command deletes the second style rule from the first style sheet in a document:
Note that the equivalent method under the IE DOM before IE9 is removeRule() .
In general, you rarely will need to work with style sheets and style rules through
JavaScript. It's usually easier and more efficient to work directly with the style sheet files
themselves, perhaps using a style sheet switcher if you need to replace one style sheet or
one style sheet rule with another.
Understanding Calculated Styles
The final style that the browser applies to any page element is known as a calculated
style . This style is not specified in any one location, but is based on a calculated weight-
ing of all of the style rules found within embedded and external style sheets, inline styles,
and the style rules built into the browser itself.
When you use the style property in your JavaScript code, you are working only with
the object's inline style attribute. If instead you need to access the final styles as calcu-
lated by your browser, you can use the method
getComputedStyle( object , pseudo )
where object is a page object and pseudo is a text string containing a pseudo-element
such as “:before” , “:after” , “:first-line” , or “:first-letter”, or null if no
pseudo-element is used in the style.
The getComputedStyle() method returns a CSSStyleDeclaration object that con-
tains all of the styles that the browser has calculated for that page object. For example,
the following code retrieves the calculated styles for the first paragraph of the current
Web document:
var para1 = document.getElementsByTagName(“p”)[0];
var p1Styles = getComputedStyle(para1, null);
To view the value of a specific calculated style property, you apply either
StyleDeclaration .getPropertyValue( styleText )
StyleDeclaration . style
to the style declaration object, where StyleDeclaration is a CSSStyleDeclaration
object, styleText is a text string containing a CSS style property, and style is the
JavaScript name of a style property. Thus, to view the font size of the first paragraph from
the previous code, you could use either of the following expressions:
Calculated styles are read-only values and cannot be changed via JavaScript. The values
are expressed in absolute units based on how the browser renders the object. For exam-
ple, any calculated property that measures a size is expressed only in pixels. Finally, you
cannot access shortcut properties but only the properties that deal with the rendering of
specific objects. Thus, you cannot access the margin property, but you can access the
margin-top property.
Versions of Internet Explorer before IE9 don't support the getComputedStyle()
method; instead they support the following:
object .currentStyle[ styleText ]
object .currentStyle. style
Search WWH ::

Custom Search