194Part IIIDocument Objects ReferenceDynamic stylesFor dynamic styles, both (Geocities web hosting)

194Part IIIDocument Objects ReferenceDynamic stylesFor dynamic styles, both the IE4+ and W3C object models provide access to stylesheet set- tings via the styleproperty of any HTML element. This simplifies matters because you canwrap modifications to styleproperties inside ifclauses that check for the existence of thestyleproperty for the specified object: function hilite(elem) { if (elem.style) { elem.style.fontWeight = bold ; } } If the event handler that triggers the change can be localized to the affected element (forexample, an onmouseoverevent handler for a spanelement surrounding some text), theevent doesn t fire in browsers that don t also support the styleproperty. (By good fortune, browsers that implement the styleproperty also expose all elements to the object model.) To compensate for the differences in object references between the IE4+ and W3C models, you can pass the object as a parameter to event handler functions: This technique obviates the need to use browser version detection because the functionsinvoked by the event handlers do not have to build DOM-specific references to the objects toadjust the style. Branching variablesIf, for now, you continue to be more comfortable with browser version detection than objectdetection, you can apply version detection for this middle ground scenario by establishingbranches for the IE4+ and W3C object models. Global variables that act as flags elsewhere inyour page s scripts are still the primary mechanism. For this scenario, you can initialize twoglobal variables as follows: function getIEVersion() { var ua = navigator.userAgent; var IEoffset = ua.indexOf( MSIE ); return parseFloat(ua.substring(IEoffset+5, ua.indexOf( ; , Ieoffset))); } var isIE4 = ((navigator.appName.indexOf( Microsoft ) == 0 && parseInt(getIEVersion()) >= 4)); var isW3C = (document.documentElement) ? true : false; Notice how the getIEVersion()function digs out the precise IE version from deep withinthe navigator.userAgentproperty. Both global variables are Boolean values. While eachvariable conveys valuable information on its own, the combination of the two reveals evenmore about the browser environment if necessary. Figure 14-4 shows the truth table for usingthe AND (&&) operator in a conditional clause with both values. For example, if you need abranch that works only in IE4, the ifclause isif (isIE4 && !isW3C) {…} The overlap between MS and the W3C object models in IE5+ means that you need to deter- mine for each branch which model to use when the script is running. This governs the orderof nested ifconditions when they arise. If you trap for the W3C version first, IE5+ runs thebranch containing the W3C DOM syntax.