Java Reference
In-Depth Information
}
.newStyle
{
font: italic 12pt arial;
text-decoration: underline;
}
The fi rst class, called defaultStyle , is the rule fi rst applied to the <div/> element. It declares a nor-
mal 12-point Arial font with no underlining. The second class is called newStyle . This class contains
style declarations to specify 12-point italic Arial that is underlined. With these changes, the <div/>
element defi nition is changed to use the defaultStyle CSS class:
<div id=”divAdvert” class=”defaultStyle” onmouseover=”divAdvert_onMouseOver()”
onmouseout=”divAdvert_onMouseOut()”>
Here is an advertisement.
</div>
Notice that the id attribute is the same; you still need to access the element in order to change its
className property. The onmouseover and onmouseout event handlers remain the same, as you need
the same behavior in the style object example.
The fi nal change is in the JavaScript itself. When the mouseover event fi res on the element, the
divAdvert_onMouseOver() function is called. This function consists of two lines of code as opposed
to the three lines you used for the style object.
function divAdvert_onMouseOver()
{
var divAdvert = document.getElementById(“divAdvert”);
divAdvert.className = “newStyle”;
}
The fi rst statement retrieves the <div/> element by using the getElementById() method. The function
then changes the className property to the value newStyle. With this line, the divAdvert element
takes on a new style rule and the browser changes the way it looks.
When you move your mouse pointer off of the text, the mouseout event fi res and divAdvert_
onMouseOut() executes. This function is almost identical to divAdvert_onMouseOver() , except
that the className is set back to its original value:
function divAdvert_onMouseOut()
{
var divAdvert = document.getElementById(“divAdvert”);
divAdvert.className = “defaultStyle”;
}
By setting className back to defaultStyle, the browser displays the <div/> element as it previously
did, with no italics or underlining.
Although it wasn't demonstrated here, the HTML class attribute, and thus the className property,
can contain multiple CSS class names. You'll see more about multiple class names in Chapter 15.
Search WWH ::




Custom Search