Main Page

Computed styles

In this example, three
<div/>
elements have a CSS class of
“special”
. When the button is clicked,
style.backgroundColor
is set to
“blue”
, thus changing the background color of all three elements.
Because of this side effect, it is always better to modify the
style
object of an individual element instead
of the one on a CSS rule. Changes to an element’s
style
object override the corresponding setting on the
CSS rule:
<html>
<head>
<title>Accessing Style Sheets Example</title>
<style type=”text/css”>
div.special {
background-color: red;
height: 10px;
width: 10px;
margin: 10px;
}
</style>
<script type=”text/javascript”>
function changeBackgroundColor() {
var oDiv = document.getElementById(“div1”);
oDiv.style.backgroundColor = “blue”;
}
</script>
</head>
<body>
<div id=”div1” class=”special”></div>
<div id=”div2” class=”special”></div>
<div id=”div3” class=”special”></div>
<input type=”button” value=”Change Background Color”
onclick=”changeBackgroundColor()” />
</body>
</html>
This example changes the background color of only the first
<div/>
by modifying its
style
object; the
other
<div/>
elements are unaffected by the change.
Computed styles
In addition to the
style
object of elements and CSS rules is the
computed style
of an element. The
com-
puted style
is made up of all the style information from inline styles and CSS rules to give a true indica-
tion of how the element is being represented on the screen. As usual, Internet Explorer and the DOM
differ in their implementations.
Computed styles in IE
Microsoft offers a
currentStyle
object on each element that includes all properties from the element
background-color
object as well the properties from any relevant CSS rule’s
style
object. The
currentStyle
object works in the exact same way as the
style
object, with all the same properties
and methods. This means that even if a background color is defined in a CSS rule,
currentStyle.
backgroundColor
still contains the correct value:
312
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 312


JavaScript EditorFree JavaScript Editor     Ajax Editor


©