Formatting Text Fields with Cascading Style Sheets


Cascading Style Sheets (CSS) have become an essential tool in the creation of modern Web pages because of the extensive formatting capabilities they provide. With Flash MX 2004, text fields now have access (albeit somewhat limited) to that same power.

NOTE

This lesson is not intended to be an extensive overview of Cascading Style Sheets, but rather a simple introduction.


A Cascading Style Sheet is a set of rules that describe how various elements are styled and formatted in a tag-based document. Although this might sound complicated, it's actually very simple. As always, the best learning tool is an example.

Imagine you have an HTML document structured like this:

 <greeting>Hello!</greeting> <message>I hope to see you soon.</message> <signature>Derek</signature> 

This document doesn't contain any of the normal HTML tags. Instead, it contains text placed between custom tags that we made up. This is the first part of the Cascading Style Sheet equation; next, we create our style sheet to describe the formatting that each of these tags represents:

 //this is our cascading style sheet greeting {   color: #663399;   font-family: Arial, Helvetica, sans-serif;   font-size: 16px;   font-weight: bold;   display: block; } message {   color: #FF3300;   font-size: 12px;   font-weight: normal;   display: block; } signature {   color: #990000;   font-size: 14px;   font-weight: italic;   display: block; } 

This style sheet contains three rules: greeting, message, and signature. The formatting of each rule is defined within the curly braces. Each line within the curly braces represents a formatting property (color, font-family, font-size, and so on) followed by a colon (:), followed by the value of the property, followed by a semicolon (;).

When this style sheet is applied to our HTML document, text between specific tags takes on the formatting of that tag as defined in the style sheet; therefore, the text "Hello!" appears in a purple, bold, 16-pixel, sans-serif font.

graphics/14inf16.gif

There are major benefits to using style sheets. Formatting your document is a breeze because the styling of elements requires the use of a single tag, as opposed to a bunch of nested tags. Another benefit is that if you have several hundred or even thousand HTML documents that get their styling via a style sheet, updating the rules in that single style sheet automatically updates the formatting of all those documents.

Although the standard that defines modern Cascading Style Sheet usage allows for some extensive formatting capabilities, Flash's implementation of Cascading Style Sheet functionality is somewhat limited. We'll discuss this in a moment, but now let's look at how Cascading Style Sheets are used in Flash.

Cascading Style Sheets can be used in Flash to define how text displayed in a dynamic text field should be formatted. The CSS can be defined internally within a movie using ActionScript, or can exist externally from Flash in a text document with a .css file extension. Creating and using Cascading Style Sheets within Flash requires use of the StyleSheet object. The syntax used to define the rules in the style sheet varies depending on whether the style sheet is internal or external. To help bring this all together, let's look at an example:

 var myStyleSheet:TextField.StyleSheet = new TextField.StyleSheet(); 

This line creates a StyleSheet object named myStyleSheet. The setStyle() method is used to define rules for this object within Flash:

 myStyleSheet.setStyle("greeting", {   color: '#663399',   fontFamily: 'Arial, Helvetica, sans-serif',   fontSize: '16',   fontWeight: 'bold',   display: 'block' }); 

This syntax creates a greeting rule (similar to the one discussed earlier) within the myStyleSheet object. However, there are some syntactical differences between this definition and the one shown earlier. The syntax shown earlier represents the standard syntactical structure of a Cascading Style Sheet (including external style sheets that would be loaded into Flash). The syntax shown above for defining a style is unique to ActionScript, and should only be used when defining rules using the setStyle() method.

The main differences to note here are that the style is defined within parentheses; the style's name is within quotes, followed by a comma; property values are between single quotes (''), property settings are terminated by commas instead of semicolons; and the last property definition (in this case, display) is not terminated by anything. Another subtle difference is the fact that standard style sheet syntax defines property names using hyphens (font-family, font-weight, and so on), but internally these same properties are defined by removing the hyphen and using an uppercase character instead (fontFamily, fontWeight, and so on).

graphics/14inf17.gif

To apply this style sheet to a text field, you simply set that text field's styleSheet property like this:

 myTextField_txt.styleSheet = myStyleSheet; 

Now, whenever any text loaded into that field makes use of the <greeting> tag, that text is styled according to the greeting rule:

 myTextField_txt.htmlText = "<greeting>Hello!</greeting>"; 

NOTE

Although it should be obvious, a text field must be set to render HTML for style sheets to work in that field.


Using external .css files is a bit different, yet still requires the use of a StyleSheet object. Let's look at another example (which assumes that there is an external .css file named myCSS.css containing style rules):

 var myStyleSheet:TextField.StyleSheet = new TextField.StyleSheet(); myStyleSheet.onLoad = function(){   myTextField_txt.styleSheet = myStyleSheet; } myStyleSheet.load("myCSS.css"); 

The first line of this script creates a StyleSheet object for holding the external style sheet rules. The next several lines assign that object an onLoad event handler so that when the external style sheet has completely loaded into it, that object is set as the styleSheet property of the myTextField_txt text field. The last line begins the loading of the external CSS file.

As mentioned earlier, Flash's implementation of Cascading Style Sheets is somewhat limited. It offers support for the following style properties (shown using their standard HTML names followed by their ActionScript names):

  • color (color)

  • display (display)

  • font-family (fontFamily)

  • font-size (fontSize)

  • font-style (fontStyle)

  • font-weight (fontWeight)

  • margin-left (marginLeft)

  • margin-right (marginRight)

  • text-align (textAlign)

  • text-decoration (textDecoration)

  • text-indent (textIndent)

NOTE

For a complete listing of acceptable values for these properties, consult the ActionScript dictionary.


In the following exercise, we set up our Flash browser so the user can change the formatting of the loaded HTML pages via submenu choices on the Style menu. The exercise uses both internally and externally defined style rules. The externally defined rules are contained in an external .css file that will be loaded as needed.

  1. Open flashBrowser2.fla.

    Because this exercise is a continuation of the preceding one, you should be familiar with the elements within the project, including the MenuBar component instance and the text field named window_txt where the external HTML files are loaded. In this exercise, we'll simply add ActionScript to Frame 1 of the Actions layer.

  2. Using your operating system's directory-exploring application, navigate to the Lesson14/Assets directory and locate the following files:

    • home.htm

    • science.htm

    • external.css

    The first two files are the HTML documents that our browser is already set up to load. The other file is an external .css file, which our application will load and use.

  3. Using your favorite HTML editor, open home.htm.

    We opened and looked at this document in the preceding exercise, but with a different purpose. This time, notice how various portions of text are placed between tags that we defined. A total of seven custom tags are used, including these:

    • <headline>

    • <headlineemphasis>

    • <subheadline>

    • <author>

    In addition, the text includes a hyperlink (<a>). This is not a custom tag, but rather a normal HTML tag; you'll soon see how style sheet formatting can be applied even to standard HTML tags.

    graphics/14inf18.gif

    NOTE

    The science.htm file uses the same tags.

    Let's look at the external.css file.

  4. Using your favorite text editor (or HTML editor, if it supports displaying CSS files), open external.css.

    Using standard CSS syntax, this file contains rules for every one of the custom tags contained in our HTML files.

    You are now armed with enough information to complete the browser project.

    graphics/14inf19.gif

  5. Return to Flash. With the Actions panel open, select Frame 1 of the Actions layer and add the following script at the end of the current script:

     var windowCSS:TextField.StyleSheet = new TextField.StyleSheet(); 

    This step creates the windowCSS StyleSheet object, which handles the application's style sheet needs.

  6. Add the following function definition:

     function setCSS(cssStyle:String){   if(cssStyle == "internal"){   }else{   } } 

    This step is the beginning of the setCSS() function. We'll add script to this function over the next couple of steps. Before we do that, however, it's important to remember that our application was set up in the preceding exercise to call this function when either the Style 1 or Style 2 submenu choice was selected from the Style menu. At the time we coded that functionality, we specified that this function would be passed a value of "internal" if Style 1 was selected, but a value of "external" if Style 2 was selected. The if statement within the function evaluates this passed-in value and causes the function to react accordingly.

    Over the next couple of steps, we'll use this if statement to tell the function to use internal style rules when "internal" is passed, but load an external CSS file and use those style rules if "external" is passed.

  7. Add the following script within the if leg of the conditional statement:

     with(windowCSS){   setStyle("headline", {   color: '#333333',     fontFamily: 'Arial, Helvetica, sans-serif',     fontSize: '20',     fontWeight: 'bold',     marginLeft: '4',     display: 'block'   });   setStyle("headlineemphasis", {     color: '#8F1D03',     fontWeight: 'normal',     fontStyle:'italic',     display: 'inline'   });   setStyle("subheadline", {     color: '#333333',     fontFamily: 'Arial, Helvetica, sans-serif',     fontSize: '15',     fontWeight: 'bold',     marginLeft: '6',     display: 'block'   });   setStyle("author", {     color: '#8F1D03',     fontFamily: 'Arial, Helvetica, sans-serif',     fontSize: '12',     fontWeight: 'normal',     fontStyle:'italic',     marginLeft: '8',     display: 'block'   });   setStyle("mainbody", {     color: '#666666',     fontFamily: 'Arial, Helvetica, sans-serif',     fontSize: '12',     fontWeight: 'normal',     marginLeft: '4',     marginRight: '6',     display: 'block'   });   setStyle("bodybold", {     fontWeight: 'bold',     display: 'inline'   });   setStyle("bodyitalics", {     fontStyle: 'italic',     display: 'inline'   });   setStyle("a:link", {     color: '#00389E'   });   setStyle("a:hover", {     textDecoration: 'underline'   }); } window_txt.styleSheet = windowCSS; 

    Although this script is lengthy, it's actually quite simple. When the function is passed the value "internal", this section of script is executed. The first part of the script uses a with statement to create the styles in the windowCSS StyleSheet object for all the custom tags that our HTML document uses. The last line of the script applies the windowCSS StyleSheet object to the window_txt text field, causing text within that field to take on the formatting shown here.

    There are a couple of important points to mention about these styles before we move on. Note that some styles have been defined using a display property of block; others have this property set as inline. (This is also true of the external .css file.) A rule where the display property has been set to block indicates that Flash should automatically place a line break before and after the section of text styled with that rule. Consider this as having the same effect as the paragraph (<p>) HTML tag. A value of inline indicates that content formatted with that rule should appear on the same line as preceding and following content. This is similar to the effect of bold (<b>) or italic (<i>) tags in HTML. Flash also supports a value of none for this property. This setting hides any content styled with that rule. Switching this property value from none to block or inline within the style sheet is an easy way to turn certain sections of content on and off.

    graphics/14inf20.gif

    Finally, the last two style sets refer to hyperlinks how they're normally styled, and how a link looks when the user mouses over the link. Yes, you can also define how content formatted with built-in HTML tags looks. For example, to define the appearance of text within an HTML paragraph tag, you use the following syntax:

     myStyleSheet.setStyle("p", {   //property settings }); 

  8. Add the following script within the else leg of the conditional statement:

     windowCSS.onLoad = function(){   window_txt.styleSheet = windowCSS; } windowCSS.load("external.css"); 

    This script takes care of what occurs when the function is passed a value of "external". When this happens, an onLoad event is assigned to the windowCSS StyleSheet object, which states that when the external .css file has finished loading into the windowCSS object, that object will be set as the styleSheet property of window_txt. This action causes the rules defined in the external style sheet to be applied to the HTML document currently loaded into window_txt.

    The last line begins loading the external style sheet into windowCSS.

    When we load an external style sheet into the same StyleSheet object that had internally defined styles (as discussed in Step 7), only styles with the same name in both definitions are updated. For example, in Step 7 we internally created a style named subheadline and defined its properties. If the externally loaded .css file defines a property with the same name, the external definition of the rule overwrites the internally defined rule when that file is loaded. If the external .css file has no rule named subheadline, however, the formatting of the internal version of the rule remains intact. The same logic is true conversely: internally defined styles can overwrite externally loaded styles.

  9. Add the following two lines at the end of the current script:

     setCSS("internal"); loadPage("home.htm"); 

    Our application is currently set up to load and style content only when a menu choice is selected, meaning that the content window of the browser is blank on loading. These two lines fix that problem by calling the setCSS() and loadPage() functions immediately when the application loads.

    It's time to do a final test.

  10. Choose Control >Test Movie.

    When the movie appears, the home.htm page is loaded into the window_txt text field and is formatted using the internally defined style rules, as discussed in Step 7. If you select Style 2 from the Style menu, the external CSS file is loaded into the application, and the styles defined in it are used as discussed in Step 8.

  11. Close the test movie and save your work as flashBrowser3.fla.

    This lesson taught you the extreme versatility of text fields and how they can be created, controlled, and configured dynamically to enhance your projects in many ways.



Macromedia Flash MX 2004 ActionScript(c) Training from the Source
Macromedia Flash MX 2004 ActionScript: Training from the Source
ISBN: 0321213432
EAN: 2147483647
Year: 2005
Pages: 182

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net