IV.6. Changing Applied Style ValuesWith so much of the rendering detail for an element in the hands of style sheets, you will likely modify style values to control a variety of DHTML effects. The IE and W3C DOMs provide several ways to adjust the value of style properties being applied to an element at any given moment. The two most popular are modifications via an element's style and className properties; other approaches dive more deeply into the style sheets and their components. IV.6.1. The style PropertyPerhaps the simplest way to adjust a single style value is through an element's style property. An element's style property is, itself, an object whose properties consist of all possible style properties supported by the browser's DOM. Before going further, it is helpful to acknowledge the similarities and differences between the style objects implemented in IE for Windows and the W3C DOM (as implemented in IE 5/Mac, Mozilla, Safari, Opera, and others). Typically, browsers that implement proprietary style properties to extend the list provided by the CSS standard also expose those proprietary style properties as scriptable properties. For example, while CSS2 does not include an attribute to specify the opacity of a text element, IE and Mozilla (prior to 1.7.2) implement their own extensions for this feature (the IE opacity filter attribute and the Mozilla mozOpacity attribute). If you implement scripted styles across DOMs, be sure the styles and values you use are supported by both DOMs (as detailed in Chapter 4 of Dynamic HTML, Third Edition) or that you provide suitable workarounds. Deeper down, however, the IE and W3C style objects have different structures. In the W3C DOM's formal structure, what you think of as a style object is known as a CSSStyleDeclaration object (terminology that scripts don't work with directly). This object features a variety of methods for reading and writing style property values that are very much in keeping with the rest of the formal DOM. For example, setting the color style property of an element looks like the following: document.getElementById("myP").style.setAttribute("color", "rgb(255, 0, 0)", ""); Fortunately, the DOM standard also offers a convenient collection of properties that lets scripts access CSS properties just as IE has been doing all along. (This collection is of DOM type CSS2Properties, which is not a requirement for DOM compliance, but is supported in most non-IE browsers just the same.) This collection leads to the more common style adjustment syntax as in the following: document.getElementById("myP").style.color = "rgb(255, 0, 0)"; The significance of understanding these inner workings comes forward when considering the data types of values assigned to style object properties. The implementation of the CSS2Properties collection supports string values exclusively, even if the values consist only of numbers. This makes sense in most cases, because even length values typically have numeric values followed by unit types, such as "14px". But also be aware that several IE-only style object attributes require either numeric or Boolean values. For example, IE's style.posLeft property consists of only the numeric portion of the string-based style.left property. We'll now examine one way of cycling a chunk of text through a sequence of colors by adjusting style properties. Example IV-7 shows a version using W3C DOM referencing syntax. A single span element in the body has the color property of its style changed in a function that is invoked often enough (via setInterval( )) to run through the cycle seven times, and then stop (to prevent user nausea). For programming convenience, the color names are stored in a global variable array, with other global variables maintaining a record of the color currently showing and the elapsed number of color changes. No positioning or other tactics are required. Example IV-7. Inline text color change via the style property
Any valid color string value could work in this code. Chapter 4 of Dynamic HTML, Third Edition explains color value formats for style attributes. IV.6.2. The className PropertyAnother popular way to modify styles applied to an element is to predefine rules for more than one class selector, and then use scripts to switch the selector assigned to an element's className property. This approach is particularly convenient if the changes you wish to make affect multiple style properties. Example IV-8 builds upon Example IV-7 by defining four style rules, each with a different class selector. The array for this version contains not color values, but class names. The repeated call to cycleColors( ) then simply assigns the next name in sequence to the span element's className property. Each change of the className property changes both the color and border style properties of the span element. Example IV-8. Inline style change via theclassName property
IV.6.3. Other TechniquesThat the IE and W3C DOMs expose not just style elements as objects, but also their content as styleSheet objects (except in Opera), might lead some scripters to get perhaps too creative in modifying applied styles. Each <style> or <link rel="stylesheet"> tag in a document creates a styleSheet object that is accessible through the document.styleSheets array. If you specify just one <style> tag in the document, document.styleSheets[0] returns a reference to that styleSheet object. From that reference, a script can inspect and modify the contents of the style sheet, albeit via occasionally different syntax for IE and W3C DOMs (IE 5/Mac observes both syntaxes). Table IV-1 lists the most important styleSheet object properties implemented in the two DOMs.
Each styleSheet object has a property that returns an array of rules that belongs to the style sheet. The IE DOM calls these objects rule objects; the W3C calls them cssRule objects. You can reference a rule via its numeric index within the array. For example, here's a reference to the third rule in a page's only style sheet via the W3C DOM: var oneRule = document.styleSheets[0].cssRules[2]; In IE syntax (required for IE/Windows), the expression is: var oneRule = document.styleSheets[0].rules[2]; Properties of an individual rule object (regardless of how you reference the object) are a bit thin, and only partially helpful across DOMs. Both models support the selectorText property, which returns a string of the selector for the rule (although IE returns tag type selectors in uppercase, regardless of the source code case). Only the W3C cssRule object provides a direct cssText property to get the actual text. But both DOMs provide a style property, which returns a style (or W3C CSSStyleDeclaration) object whose properties reveal the individual style property settings for the rule. The following function demonstrates the cross-DOM syntax that sets the font-size attribute of a p-selectored rule in a style sheet: function setPSize(n, units) { var sheets = document.styleSheets[0]; var ruleList = (typeof sheets.cssRules != "undefined") ? sheets.cssRules : ((typeof sheets.rules != "undefined") ? sheets.rules : null); if (ruleList) { for (var i = 0; i < ruleList.length; i++) { if (ruleList[i].selectorText.toLowerCase( ) == "p") { ruleList[i].style.fontSize = n + units; // e.g., "px" break; } } } } Additional facilities for modifying styleSheet objects include methods for adding and deleting individual rules within the styleSheet object (with incompatible syntax for IE and W3C DOMs). You can learn the details in Chapter 2 of Dynamic HTML, Third Edition. Despite the substantial flexibility available through the styleSheet object, you will experience better reliability and compatibility (especially with Opera) if you perform your style changes via the style or className properties of the element you wish to modify. Working with styleSheet objects is best left to those times when scripts are creating new style sheets or rules on the fly. |