Main Page

DOM style methods

onmouseout=”this.style.backgroundColor = ‘red’”></div>
</body>
</html>
When you move the mouse over the red
<div/>
, it changes to blue; when you mouse out, it returns to
red. Note that the event handlers use the
this
keyword to refer to the
<div/>
itself and gain access to
its
style
object.
The style object also has a property called
cssText
that contains the CSS string describing the style of
the element:
<html>
<head>
<title>Style Example</title>
</head>
<body>
<div id=”div1”
style=”background-color: red; height: 50px; width: 50px”
onclick=”alert(this.style.cssText)”></div>
</body>
</html>
When you click on the
<div/>
in this example, the text
“background-color: red; height: 50px;
width: 50px”
displays.
DOM style methods
The DOM also described several methods for the style object, all designed to interact with individual
parts of the CSS style definition:
?
getPropertyValue(
propertyName
)
— Returns the string value of the CSS property
propertyName
. The property must be specified in CSS style, such as
“background-color”
instead of
“backgroundColor”
.
?
getPropertyPriority()
— Returns the string
“important”
if the CSS property
“!important”
is specified in the rule; otherwise it returns an empty string
?
item(
index
)
— Returns the name of the CSS property at the given
index
, such as
“background-color”
?
removeProperty(
propertyName
)
— Removes
propertyName
from the CSS definition
?
setProperty(
propertyName
,
value
,
priority
)
— Sets the CSS property
propertyName
to
value
with the given
priority
(either
“important”
or an empty string)
Here’s a simple example:
<html>
<head>
<title>Style Example</title>
<script type=”text/javascript”>
function useMethods() {
305
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 305


JavaScript EditorFree JavaScript Editor     Ajax Editor


©