1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning JavaScript Third Edition phần 7 ppt

79 344 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

The second problem is how to handle the event. The image rollover DHTML script must retrieve the ele- ment that the event fired upon. In IE, this element is retrieved with the srcElement property. In non-IE browsers, the target property is the desired property. Thankfully, this problem has a straightforward solution: branch the code according to which browser is displaying the page. In Chapter 5 you learned how to use object detection to determine which browser the user is using. Do the same thing here. Consider the following code: var elementTarget; //contains either the srcElement or the target property if (evt.srcElement) { //The browser is IE elementTarget = evt.srcElement; } //more code here The first line of this code creates a variable called elementTarget, which stores either the srcElement or target property, depending upon the browser that loaded the page. The next line uses object detec- tion to determine the browser. In this case, the srcElement is checked. If it exists, then the browser is IE, and you can safely use the property. Next, write code for the other browsers. If the srcElement property doesn’t exist, the browser obvi- ously isn’t IE, and you can use the target property. var elementTarget; //contains either the srcElement or the target property if (evt.srcElement) { //The browser is IE elementTarget = evt.srcElement; } else { //The browser is non-IE elementTarget = evt.target; } Now you can use the elementTarget variable to access the HTML element that the event was fired upon. The following example shows the only time the code branches to accommodate the differing browsers. Try It Out Cross-Browser Image Rollover This example modifies the image rollover you previously wrote to work in all modern browsers. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head> <title>Cross-browser Image Rollover</title> <script type=”text/javascript”> function image_eventHandler(evt) { var elementTarget; if (evt.srcElement) { //The browser is IE elementTarget = evt.srcElement; 451 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 451 } else { //The browser is non-IE elementTarget = evt.target; } if (evt.type == “mouseover”) { //The mouse rolled over the image. elementTarget.src = “o.gif”; //So change the image’s src property. } if (evt.type == “mouseout”) { //The mouse moved out. elementTarget.src = “x.gif”; //So change it back to the original. } } </script> </head> <body> <img src=”x.gif” onmouseover=”image_eventHandler(event)” onmouseout=”image_eventHandler(event)” /> </body> </html> Save this file as CB_image_rollover.htm (CB means cross-browser). Open this page with any modern browser (IE, Firefox, Opera, or Safari), and you’ll see something similar to Figure 12-5. Figure 12-5 452 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 452 Move the mouse pointer over the image, and it changes to an O (see Figure 12-6). Figure 12-6 How It Works A single <img/> element resides in the page’s body. The src attribute is set to x.gif. Also, onmouseover and onmouseout event handlers are set to the value of image_eventHandler(event). <img src=”x.gif” onmouseover=”image_eventHandler(event)” onmouseout=”image_eventHandler(event)” /> This not only suits the needs of non-IE browsers, but also passes the IE-specific global event object to the image_eventHandler() function. This enables the function to use both event objects, depending on which browser displays the web page. In the script block, the image_eventHandler() function is defined. function image_eventHandler(evt) { var elementTarget; //more code here } 453 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 453 It accepts an event object as an argument, and the first line creates a variable called elementTarget. Next, the code branches to accommodate the different browsers: function image_eventHandler(evt) { var elementTarget; if (evt.srcElement) { //The browser is IE elementTarget = evt.srcElement; } else { //The browser is non-IE elementTarget = evt.target; } //more code here } This code consolidates the differing event object implementations into one usable variable: elementTarget. To do this, use object detection to determine the browser and assign the appropriate property to the elementTarget variable. Since this function handles two events, it needs to determine which event called the function. As you already know, the type property contains this information. First check to see if the event was caused by the mouse pointer moving over the image element: function image_eventHandler(evt) { var elementTarget; if (evt.srcElement) { //The browser is IE elementTarget = evt.srcElement; } else { //The browser is non-IE elementTarget = evt.target; } if (evt.type == “mouseover”) { //The mouse rolled over the image. elementTarget.src = “o.gif”; //So change the image’s src property. } //more code here } If this is the case, change the src property of the <img/> element to o.gif, which changes the picture that is displayed to the user. Notice that this is where the elementTarget variable is used. Next, check to see if the event was caused by the user moving the mouse pointer off of the image: function image_eventHandler(evt) { var elementTarget; if (evt.srcElement) { //The browser is IE elementTarget = evt.srcElement; } else { //The browser is non-IE elementTarget = evt.target; } if (evt.type == “mouseover”) { //The mouse rolled over the image. 454 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 454 elementTarget.src = “o.gif”; //So change the image’s src property. } if (evt.type == “mouseout”) { //The mouse moved out. elementTarget.src = “x.gif”; //So change it back to the original. } } This code compares the type property to the string mouseout and changes the image’s src property back to x.gif if this event was fired. And with these final few lines of code, your first cross-browser DHTML script is complete! These examples have focused on using the event handler attributes of HTML elements. The next section focuses on using event handlers that are assigned through JavaScript. Event Handlers as Properties Revisited There is one glaring difference between assigning event handlers with HTML attributes and assigning them with JavaScript. With the HTML attributes, you were able to pass arguments to the function han- dling the event (for example, the event object). When using properties, though, you cannot pass any arguments to the function when assigning the event handler: document.images[0].onmouseover = image_eventHandler(event); //This is wrong! document.images[0].onmouseover = image_eventHandler; //This is correct. This isn’t really a problem for IE, as the event object is a part of the window object, which is global. For non-IE browsers, the browser automatically passes the event object to the event handler when the event fires. So handling events in this fashion is almost identical to handling them as you did in the previous section. Try It Out Image Rollover with Property Event Handlers The following HTML is yet another implementation of the image rollover script: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head> <title>Cross-browser Image Rollover</title> </head> <body> <img src=”x.gif” /> <script type=”text/javascript”> function image_eventHandler(evt) { var elementTarget; var eventType; if (window.event) { //The browser is IE elementTarget = window.event.srcElement; eventType = window.event.type; } else { //The browser is non-IE 455 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 455 elementTarget = evt.target; eventType = evt.type; } if (eventType == “mouseover”) { //The mouse rolled over the image. elementTarget.src = “o.gif”; //So change the image’s src property. } if (eventType == “mouseout”) { //The mouse moved out. elementTarget.src = “x.gif”; //So change it back to the original. } } document.images[0].onmouseover = image_eventHandler; document.images[0].onmouseout = image_eventHandler; </script> </body> </html> Save this file as CB_image_rollover_property_events.htm. When loaded into a browser, a picture of an X is visible. How It Works In the body of the page, a single <img/> element is defined. This is a simple element: Only the src attribute is used. <img src=”x.gif” /> Here’s where things start to change. Instead of putting the <script/> element in the head of the page, you put it in the body. This is done for one reason: The image needs to be loaded into the document before it can be accessed with JavaScript. Attempting to access an HTML element before it’s loaded into the document results in an error. You can’t access an HTML element in JavaScript if it hasn’t been loaded by the browser. The first thing in the script block is the image_eventHandler() function. It is essentially the same as in the prior sections, but this iteration contains a few changes. The first is the addition of the eventType variable. This variable will contain the value of the type property of the event object. function image_eventHandler(evt) { var elementTarget; var eventType; //more code here } You do this because the function now has to handle two different event objects. The evt parameter is used only in non-IE browsers; the following line generates an error if you run it in IE: alert(evt.type); //throws an error in IE 456 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 456 This happens because IE does not pass a value to event handlers when the event fires. So when branch- ing the code to assign elementTarget, you must also assign the eventType variable its value, like this: function image_eventHandler(evt) { var elementTarget; var eventType; if (window.event) { //The browser is IE elementTarget = window.event.srcElement; eventType = window.event.type; } //more code here } This code uses the global window.event object to retrieve the event’s type and assign it to eventType. Next, get the same information for the non-IE browsers: function image_eventHandler(evt) { var elementTarget; var eventType; if (window.event) { //The browser is IE elementTarget = window.event.srcElement; eventType = window.event.type; } else { //The browser is non-IE elementTarget = evt.target; eventType = evt.type; } //more code here } This code uses the evt parameter to retrieve the target and type properties. At this point you have the information you need; now it’s time to use it in changing the image element’s src property. function image_eventHandler(evt) { var elementTarget; var eventType; if (window.event) { //The browser is IE elementTarget = window.event.srcElement; eventType = window.event.type; } else { //The browser is non-IE elementTarget = evt.target; eventType = evt.type; } if (eventType == “mouseover”) { //The mouse rolled over the image. elementTarget.src = “o.gif”; //So change the image’s src property. } 457 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 457 if (eventType == “mouseout”) { //The mouse moved out. elementTarget.src = “x.gif”; //So change it back to the original. } } This code hasn’t changed from the previous examples: It determines what event called the function and changes the src property accordingly. Now all that is left is to wire up the events. Do so by using the onmouseover and onmouseout properties of the image element. document.images[0].onmouseover = image_eventHandler; document.images[0].onmouseout = image_eventHandler; This code retrieves the image element by using the images collection. There is only one image in the document. Therefore, the index of 0 is used to retrieve the element. These sections have walked you through many rollover examples. The next section departs from JavaScript and introduces you to Cascading Style Sheets. CSS: A Primer Cascading style sheets (CSS) is an important technology that developers use to build many DHTML scripts. Cascading Style Sheets is a language that enables you to apply a set of styles to various HTML tags. For example, you may want all <h1/> elements in the web page to be colored blue and underlined. Before CSS you would do this with various formatting tags, such as <font> and <u>. This approach worked; however, it caused a few problems. The first problem with this approach is that you need to wrap the content with these formatting tags, and styling different pieces of content the same way requires repeated tag use. This results in extra work for web page authors. Also, changing an existing style (say blue underlined text ) to a new style (red boldface text), requires the change of every <font> and <u> tag throughout the document. To add to this problem, you may want to set a very specific size for the text of the <h1> tags. The sizes offered by the font are very limited, and those few sizes enable you to specify only whether the font should be larger or smaller than normal. The font sizes are relative to the font size the user has set in her browser. This makes it possible for text to be rendered in an unreadable size. HTML also does not give you control over where elements appear in the page. The browser displays HTML elements according to where the tags appear in the source code. Therefore, the following HTML will always display Hello on the first line and World on the second line: <p>Hello</p> <p>World</p> This is what is referred to as the document flow —how the browser naturally displays the web page. Without CSS, it is not possible to change the document flow. You can use formatting tags for different types of positioning (like lists or tables), but you can’t specify an exact position. 458 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 458 CSS solves each of these problems. It enables you to specify certain styles that can be used throughout the entire web page easily and efficiently. It also gives you more control over how the web page looks, thereby giving you more power to make the page look the way you first envisioned it. Adding Some Style to HTML You can add style to an HTML page by creating style sheets within the <style> tag or by specifying style attributes in an element’s opening tag. There are a number of ways to define style, but this primer covers only three of them: ❑ Defining a style for certain HTML elements, for example a style for all paragraph elements. ❑ Creating a style class. You then specify in the class attribute of a tag the name of the style class to be applied. ❑ Specifying style for just one element. The <style> Tag You can use the first two ways of adding style mentioned in the previous list— defining a style for a type of tag and defining a style class — by creating a <style/> element inside the <head/> element. To define the style for a particular element, use the following format: elementName { style-property-name: style property value; another-style-property: another value; } This CSS code is referred to as a CSS rule. A rule consists first of a selector. A selector selects the HTML element to which the style rule will be applied. In the previous example, elementName is the selector. Any HTML element name can be used as a selector; just remember to take out the angle brackets (< and >). For example, to define a selector for all <p> tags, you would use an elementName of p. After the selector comes a set of style declarations inside the curly braces. A declaration consists of a prop- erty name, a colon (instead of an equals sign), and then the property’s value. Style declarations are sepa- rated by semicolons. For example, let’s say you want all <p> tags to be blue, in the Arial font, and 10 points in size. First create a rule to select the <p> tags. Then add the declarations by specifying the font- family , font-size, and color properties. The following code does this: <html> <head> <style> p { font-family: arial; font-size: 10pt; color: blue; } </style> </head> 459 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 459 <body> <p>Some blue arial 10 point text</p> <p>Also blue arial 10 point text</p> </body> </html> The first property specified is font-family, which is assigned the value arial. This is followed by a semicolon to mark the end of that style declaration. Next the font-size property is defined and its value set to 10pt. Finally you specify the color property and its value of blue. Both the paragraphs defined in the page will have the same font, font size, and color. If you want to define similar properties for the <td> tags, add a rule inside the <style> tag. <style> p { font-family: arial; font-size: 10pt; color: blue; } td { font-family: arial; font-size: 12pt; color: red; } </style> This CSS sets the <td> tags to have the same font family as the <p> tags, but their font’s size is larger and their text is rendered in red. This is the basic behavior of CSS, but it doesn’t help if you want some paragraphs in a larger font while others remain in the 10-point font. CSS is not limited to this basic functionality, however. You can define what are called classes: CSS rules that can be applied to a variety of elements. In fact, with CSS classes, you can make any element emulate almost any other. A class’s selector is a custom name that you define. Classes are distinguished by a dot in front of their names. The following code defines a class called heading1: <style> p { font-family: arial; font-size: 10pt; color: blue; } .heading1 { font-size: 24pt; color: orange; } </style> 460 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/07 6:17 PM Page 460 [...]... whereas for 1024 * 76 8 resolutions, it’s 1024 ,76 8, as shown in Figure 12 -7 0,0 400,300 800,600 1024 ,76 8 Figure 12 -7 If you specified that a element’s left style attribute be set to 400 pixels and its top style attribute to 300 pixels, the element’s top left-hand corner would be near the middle of a browser window on an 800 * 600 resolution display If the display were set to 1024 * 76 8, the top left-hand... through JavaScript to associate a different style rule with the element oHtmlElement.className = sNewClassName; 475 Chapter 12: Introduction to Dynamic HTML Using the className property to change an element’s style is advantageous in two ways First, it reduces the amount of JavaScript you have to write, which no one is likely to complain about Second, it keeps style information out of the JavaScript. .. Figure 12 -7 Let’s look at an example Imagine you have an absolutely positioned element at a position left of 200 and top of 100, and with other style attributes specifying it should be 200 pixels wide by 200 pixels deep and have a background color of blue Your browser window would look something like what is shown in Figure 12-8 4 67 Chapter 12: Introduction to Dynamic HTML 0,0 800,600 1024 ,76 8 Figure... with JavaScript Earlier in the chapter you learned about the position CSS property, where you can specify an element to be absolutely or relatively positioned You also learned about the top and left properties, which enable you to position the elements where you desire You can do the same thing with JavaScript by changing the values of these properties Just Move It Over There Moving content with JavaScript. .. them Changing the way an element looks consists almost exclusively of changing CSS properties for an HTML element You can do this two ways through JavaScript: You can change each CSS property, or you can change the value of the element’s class attribute 470 Chapter 12: Introduction to Dynamic HTML Using the style Property In order to change specific CSS properties, you must look, once again, to the... onmouseout=”divAdvert_onMouseOut()”>Here is an advertisement. Notice that the id attribute is the same: JavaScript still needs to access the element in order to change its className property The onmouseover and onmouseout event handlers remain the same, as you need the same functionality that style_object.htm has The last change is in the JavaScript itself When the mouseover event fires on the element, the associated divAdvert_onMouseOver()... off of the text, the mouseout event fires and divAdvert_ onMouseOut() executes This function is almost identical to divAdvert_onMouseOver(), except that the className is set back to its original value: 477 Chapter 12: Introduction to Dynamic HTML function divAdvert_onMouseOut() { //Get the element var divAdvert = document.getElementById(“divAdvert”); //Change the className divAdvert.className = “defaultStyle”;... this as style_object.htm When you run this in your browser you should see a single line of text, as shown in Figure 12-10 472 Chapter 12: Introduction to Dynamic HTML Figure 12-10 Roll your mouse over the text, and you’ll see it become italicized and underlined (see Figure 12-11) 473 Chapter 12: Introduction to Dynamic HTML Figure 12-11 And when you move your mouse off of the text, it returns back to... prepend the hexadecimal number with a pound sign (#) Hexadecimal numbers in CSS typically consist of three pairs of numbers color: #FF0000; The first pair is red (FF), the second is green (00), and the third is blue (00) You can also use three digits, like this: color: #f00; When the browser finds three-digit hexadecimal values, it converts them to a six-digit form and replicates the digits So the previous... results: var divAdvert = document.getElementById(“divAdvert”); alert(divAdvert.style.backgroundColor); alert(divAdvert.style.color); //Get the desired element //Alerts an empty string //Alerts green 471 Chapter 12: Introduction to Dynamic HTML You get these results because the style object accesses the style attribute of the element If the style declaration is set in the block, you cannot . what is shown in Figure 12-8. 0,0 800,600 1024 ,76 8 400,300 4 67 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/ 07 6: 17 PM Page 4 67 Figure 12-8 Now how can you position a paragraph. right-hand corner is at the coordinates 800,600, whereas for 1024 * 76 8 resolutions, it’s 1024 ,76 8, as shown in Figure 12 -7. Figure 12 -7 If you specified that a <div/> element’s left style attribute. = “o.gif”; //So change the image’s src property. } 4 57 Chapter 12: Introduction to Dynamic HTML 15_051511 ch12.qxp 4/13/ 07 6: 17 PM Page 4 57 if (eventType == “mouseout”) { //The mouse moved out. elementTarget.src

Ngày đăng: 09/08/2014, 14:21

Xem thêm: Beginning JavaScript Third Edition phần 7 ppt

Mục lục

    Beginning JavaScript, Third Edition

    Chapter 12: Introduction to Dynamic HTML

    Adding Some Style to HTML

    Positioning and Moving Content

    Chapter 13: Dynamic HTML in Modern Browsers

    Why Do We Need Web Standards?

    The Document Object Model

    Differences Between the DOM and the BOM

    Representing the HTML Document as a Tree Structure

    DOM Properties and Methods

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN