142 Chapter 8: Working with Text
Creating new styles with ActionScript
You can create new text styles with ActionScript by using the
setStyle() method of the
TextField.StyleSheet class. This method takes two parameters: the name of the style and an object
that defines that style’s properties.
For example, the following code creates a style sheet object named
styles that defines two styles
that are identical to those you imported earlier (see “Loading external CSS files” on page 141).
var styles = new TextField.StyleSheet();
styles.setStyle("bodyText",
{fontFamily: 'Arial,Helvetica,sans-serif',
fontSize: '12px'}
);
styles.setStyle("headline",
{fontFamily: 'Arial,Helvetica,sans-serif',
fontSize: '24px'}
);
Applying styles to a TextField object
To apply a style sheet object to a text field, you assign the style sheet object to the text field’s
styleSheet property.
textObj_txt.styleSheet = styleSheetObj;
Note: Be careful not to confuse the TextField.styleSheet property with the TextField.StyleSheet
class. The capitalization indicates the difference.
When you assign a style sheet object to a TextField object, the following changes occur to the text
field’s normal behavior:
• The text field’s text and htmlText properties, and any variable associated with the text field,
always contain the same value and behave identically.
• The text field becomes read-only and cannot be edited by the user.
• The setTextFormat() and replaceSel() methods of the TextField class no longer function
with the text field. The only way to change the field is by altering the text field’s
text or
htmlText properties, or by changing the text field’s associated variable.
• Any text assigned to the text field’s text property, htmlText property, or associated variable is
stored verbatim; anything written to one of these properties can be retrieved in the text’s
original form.
Combining styles
CSS styles in Flash Player are additive; that is, when styles are nested, each level of nesting can
contribute additional style information, which is added together to result in the final formatting.
For example, here is some XML data assigned to a text field:
<sectionHeading>This is a section</sectionHeading>
<mainBody>This is some main body text, with one
<emphasized>emphatic</emphasized> word.</mainBody>
For the word emphatic in the above text, the emphasized style is nested within the mainBody
style. The
mainBody style contributes color, font-size, and decoration rules. The emphasized
style adds a font-weight rule to these rules. The word emphatic will be formatted using a
combination of the rules specified by
mainBody and emphasized.