Main Page

JavaScript Style Property

CSS Style Attribute
JavaScript Style Property
background-color
style.backgroundColor
color
style.color
font
style.font
font-family
style.fontFamily
font-weight
style.fontWeight
To change a style’s value using JavaScript, simply assign a CSS string to the style object property. For
example, the following code changes the CSS
border
attribute of a
<div/>
to
“1px solid black”
:
var oDiv = document.getElementById(“div1”);
oDiv.style.border = “1px solid black”;
It is possible to retrieve the value of any inline styles (those assigned by using the HTML
style
attribute) by using the
style
object as well. For example, the following page displays the background
color of a
<div/>
by clicking a button:
<html>
<head>
<title>Style Example</title>
<script type=”text/javascript”>
function sayStyle() {
var oDiv = document.getElementById(“div1”);
alert(oDiv.style.backgroundColor);
}
</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 same technique can be used to apply
rollover
effects when the user moves the mouse over a given
element on the page. Although CSS Level 2 provides the
:hover
pseudo-class to provide rollover effects
on all elements, it is not supported by all browsers on all elements. To overcome this lack of support, just
use the
style
object:
<html>
<head>
<title>Style Example</title>
</head>
<body>
<div id=”div1”
style=”background-color: red; height: 50px; width: 50px”
onmouseover=”this.style.backgroundColor = ‘blue’”
304
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 304


JavaScript EditorFree JavaScript Editor     Ajax Editor


©