Recipe 8.15. Applying CSSProblemYou want to apply CSS (cascading style sheets) to a dynamic text field. SolutionUse a StyleSheet object to load the CSS from an external file, and then apply it to the text field. Optionally, use the TextLoader component. DiscussionThe StyleSheet class allows you to apply CSS to text fields in your Flash application. While there are several ways in which you can create and populate a StyleSheet object within Flash, the most useful is to load an external CSS document. You can define a CSS document using a standard text editor or a CSS editor such as Dreamweaver or Top Style. After you've defined the CSS document, save it to the same directory to which you are saving the .swf file. Then, within Flash, use the following code: // Set the text field so that it can render HTML. tField.html = true; // Create a StyleSheet object. var cssStyles:TextField.StyleSheet = new TextField.StyleSheet(); // Define an onLoad( ) event handler method for the style sheet so that it knows what to // do with the CSS once it has loaded. cssStyles.onLoad = function(bLoaded:Boolean):Void { if(bLoaded) { // Apply the style sheet to the text field. tField.styleSheet = this; // Assign the HTML text to the text field. tField.htmlText = "HTML text"; } }; // Load the CSS. cssStyles.load("CSS document"); As you can see from the code, you can apply a style sheet to a text field using the styleSheet property of the text field. You must apply the style sheet to the text field before you assign the HTML to it. You can define both tag styles and style classes in your CSS document. Flash supports the following styles:
The following is an example of a simple CSS document. The first block defines a style for a tag named <body>. The second block defines a style class named code. body { font-family: "_sans"; color: #0000FF; } .code font-family: "_typewriter"; color: #FF0000; } The following ActionScript example loads the preceding CSS from a document named styles.css and then applies it to a text field named tOutput: tOutput.html = true; var cssStyles:TextField.StyleSheet = new TextField.StyleSheet(); cssStyles.onLoad = function(bLoaded:Boolean):Void { if(bLoaded) { tOutput.styleSheet = this; tOutput.htmlText = "<body>If you want to use CSS with Flash, use a <span class='code'>StyleSheet</span> object.</body>"; } }; cssStyles.load("styles.css"); If you feel uncomfortable with the ActionScript necessary to apply CSS to a text field, you can use the TextLoader component discussed in Chapter 13 to both load text and CSS without any ActionScript code. |
Tripod >> 3pod Tips & Learning and manuals for educations