11.8 Toggling Between Style Sheets for an Element
NN 6, IE 4
11.8.1 Problem
You want to swap style sheets for an
element based on user action, such as rolling the mouse over a hot
spot or clicking on an arbitrary element.
11.8.2 Solution
First, define two style sheet rules, each with a different class
selector. Then design an event handler for the element to change the
element's
className property to the desired class
selector's identifier:
<style type="text/css">
.unhilited {background-color:white}
.hilited {background-color:yellow; text-decoration:underline}
</style>
...
<script type="text/javascript">
function setHilite(evt) {
evt = (evt) ? evt : ((window.event) ? window.event : null);
if (evt) {
var elem = (evt.srcElement) ? evt.srcElement : evt.target;
elem.className = "hilited";
}
}
function setUnHilite(evt) {
evt = (evt) ? evt : ((window.event) ? window.event : null);
if (evt) {
var elem = (evt.srcElement) ? evt.srcElement : evt.target;
elem.className = "unhilited";
}
}
...
<span class="unhilited" onmouseover="setHilite(event)"
onmouseout="setUnHilite(event)">Some potentially hot spot text.</span>
Adjusting the className property of an element as
shown here is a more stable approach for early versions of Netscape 6
instead of manipulating styleSheet objects and
their properties. It is perhaps the most widely used and supported
way to implement dynamic styles.
11.8.3 Discussion
If you are toggling the style for just a single element, you might be
tempted to use the id attribute and ID selector as
your switch point, rather than the class attribute
and selector. But an element's id
attribute should not change unless absolutely necessary.
When a script reassigns a style sheet rule to an element, none of the
CSS properties from the previous setting are inherited by the newly
assigned rule. In the preceding example, the rule with the
hilited class selector sets the
text-decoration property to underline the
element's text. But when the
unhilited rule is reapplied to the element, the
element automatically reverts to the previous value of the
text-decoration property that the element
inherited from the browser's default style sheet.
11.8.4 See Also
Recipe 11.7 for enabling or disabling a style sheet.
|