↑
Main Page
first position
var oDiv = document.getElementById(“div1”);
alert(oDiv.style.item(0)); //outputs “background-color”
alert(oDiv.style.getPropertyValue(“background-color”));
alert(oDiv.style.removeProperty(“background-color”);
}
</script>
</head>
<body>
<div id=”div1” style=”background-color: red; height: 50px; width:
50px”></div><br />
<input type=”button” value=”Use Methods” onclick=”useMethods()” />
</body>
</html>
When the button is clicked on this page, three things happen. First, the item in the first position (position
0) is displayed, which is
“background-color”
because it comes first in the
style
attribute of the
<div/>
. Second, the current value of
background-color
(red) is displayed. Finally, the
background-
color
property is removed altogether, effectively making the
<div/>
invisible.
These methods can be used in place of the various
style
object properties to accomplish the same thing.
For example, this returns the background color of the
<div/>
:
<html>
<head>
<title>Style Example</title>
<script type=”text/javascript”>
function sayStyle() {
var oDiv = document.getElementById(“div1”);
alert(oDiv.style.getPropertyValue(“background-color”));
}
</script>
</head>
<body>
<div id=”div1” style=”background-color: red; height: 50px; width:
50px”></div><br />
<input type=”button” value=”Get Background Color” onclick=”sayStyle()” />
</body>
</html>
This is a rewrite of the rollover effect using the
style
methods:
<html>
<head>
<title>Style Example</title>
</head>
<body>
<div id=”div1”
style=”background-color: red; height: 50px; width: 50px”
onmouseover=”this.style.setProperty(‘background-color’, ‘blue’, ‘’)”
onmouseout=”this.style.setProperty(‘background-color’, ‘red’, ‘’)”>
</div>
</body>
</html>
306
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 306
Free JavaScript Editor
Ajax Editor
©
→