Học JavaScript qua ví dụ part 55 doc

10 226 0
Học JavaScript qua ví dụ part 55 doc

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

Thông tin tài liệu

ptg 13.7 The event Object 499 13.7 The event Object As we have seen throughout this text, events are happening all the time with JavaScript. Event objects are sent to an event handler with each event that occurs within a docu- ment; for example, when the user clicks on the left mouse button, JavaScript registers the event, what key was pressed, its coordinates (pixel positions of where it was pressed on the screen), and so on. To learn more about what happened so that you can track problems, get pixel coordinates, find out what button was pushed or what key was released, and so on, the event object provides specific information about the event. This topic can be very confusing because W3C, Mozilla/Firefox type browsers, and Microsoft Internet Explorer differ in how events should be handled. Like economists argue over </script> </head> <body bgcolor="white"> <form> <div align="center"> <p> 1 <image src="Image/java_steam.gif" 2 onError="alert('Image is having trouble loading!')"> </p> <input type="button" value="Wake me" onClick="wakeupCall()" /> </div> </form> </body> </html> EXPLANATION 1 The <image> tag identifies the src of a .gif image to be loaded from a subdirectory called Image. 2 The onError event handler is triggered when an error occurs while loading the image. See Figure 13.28. Figure 13.28 The onError event handler was triggered because the image src was wrong (left), and after the image loads (right). EXAMPLE 13.20 (CONTINUED) From the Library of WoweBook.Com ptg 500 Chapter 13 • Handling Events taxes, trickle-up or trickle-down economics, browser companies argued over the order in which events are handled, also called event propagation. Does the event bubble up from its target or does it trickle down to its target? 13.7.1 Capturing and Bubbling (Trickle Down and Bubble Up) The way that the events are handled differs by the browser and is based on how Netscape and Internet Explorer dealt with events back in the 1990s. Suppose you have used an onClick event handler in the button of a form. The user clicks the button. What hap- pens? Netscape said that the event is captured, that is, it comes to life at the window level and trickles down the document to the form object until it finally reaches the but- ton, its target: When it reaches its target, the button, the event is fired. An analogy could be water trickling down a mountain stream until it reaches a lake at the bottom. Internet Explorer says the event springs to life for the target for which it was intended; (i.e., the button) and then sends information about the event back up from the button to the form to the document, then window, like the bubbling up effect of soda water in a glass (see Figure 13.29). Fortunately, the W3C DOM Level 2 provides an Events module that allows the DOM nodes to handle events with a combination of these methods, but defaults to the bubble- up model. We will see later how to use event handling with the DOM, how to specifically program the event to use one model or the other, cancel the bubbling effect, and so on. For now we will assume the browser is W3C compliant and defaults to bubbling. If you want to check what model your browser is using, the last exercise in this chapter pro- vides the JavaScript code for testing. We discuss bubbling and capturing again in Chap- ter 15. Figure 13.29 Bubbling and capturing. window document form button Capturing Bubbling onClick(“do something”) From the Library of WoweBook.Com ptg 13.7 The event Object 501 13.7.2 Event Object Properties Now we will look at some of the properties of the event object and how they are used to glean information about an event that has occurred. Many of the examples listed on different Web sites might not work when you try them because they were written for a specific client. You might be using Opera or Safari and think, “This doesn’t work at all. I give up.” But if you bring up Internet Explorer, the program seems to work fine. To see what does or doesn’t apply to your browser go to “Events Compatibility Table” at http://www.quirksmode.org/dom/events/index.html. Although the DOM provides a stan- dard model, not all browsers are compliant. We discuss the DOM in Chapter 15. Tables 13.8 and 13.9 provide a list of the event properties for Internet Explorer and Firefox. Table 13.8 Properties of the event Object: Internet Explorer Property What It Describes altKey, ctrlKey, shiftKey Set to true or false to test if Alt, Shift, or Control keys were pressed when the event occurred. button An integer indicating which mouse button was pressed or released, 1 = left, 2 = right, 4 = middle. If multiple buttons are pressed, the value is the sum of both buttons, such as 3 (1+2) for left and right. cancelBubble Set to true or false to cancel or enable event bubbling. To cancel across browsers, the stopPropagation() method is supported. clientX and clientY The cursor’s horizontal and vertical position in pixels, relative to the upper-left corner Web page in which the event occurred. Also good for the Mozilla/Firefox and W3C event model. fromElement, toElement Used to indicate the elements where a mouse is (mouseout and mouseover) leaving from or moving into. See relatedTarget for W3C/Firefox. keyCode The Unicode key code associated with a keypress event. Use String.fromCharCode(keyCode) to convert keycode code to a string. offsetX and offsetY The cursor’s horizontal and vertical position in pixels, relative to the container in which the event occurred, or if outside the container returns the upper left corner of the document. returnValue The return value of the event handler, either true or false. For W3C/Firefox use preventDefault() method. srcElement The element from where the event originated, not necessarily the element where it was assigned due to bubbling. Use target for Firefox. Continues From the Library of WoweBook.Com ptg 502 Chapter 13 • Handling Events srcFilter Specifies the filter object that caused an onfilterchange event. x and y The cursor’s horizonal and vertical position in pixels, relative to the document in which the event occurred. reason Used to indicate the status of a data transfer for data source objects. Table 13.9 Properties of the event Object: Mozilla Firefox Property What It Describes altKey, ctrlKey, metaKey, shiftKey Set to true or false to test if Alt, Shift, Control, or Meta keys were pressed when the event occurred (Internet Explorer doesn’t support metaKey). pageX and pageY Horizontal and vertical cursor position within a Web page, relative to the document, not supported by Internet Explorer. bubbles Set to Boolean value indicating whether or not the event bubbles. button An integer indicating which mouse button was pressed or released, 0 = left, 2 = right, 1 = middle. Slightly different in Internet Explorer, as described earlier. cancelable A Boolean value indicating whether or not the event can be canceled. charCode Indicates the Unicode for the key pressed. Use String.fromCharCode(which) to convert code to string. clientX, clientY Returns the mouse coordinates at the time of the event relative to upper- left corner of the window. currentTarget The node that this event handler is currently being run on. eventPhase An integer value indicating which phase of the event flow this event is being processed in. One of CAPTURING_PHASE (1), AT_TARGET (2) or BUBBLING_PHASE (3). layerX and layerY Returns the horizontal and vertical cursor position within a layer, not standard. relatedTarget On a mouseover event it indicates the node that the mouse has left. On a mouseout event it indicates the node the mouse has moved onto. screenX and screenY Returns the coordinates of the mouse relative to the screen when the event fired. Table 13.8 Properties of the event Object: Internet Explorer (continued) Property What It Describes From the Library of WoweBook.Com ptg 13.7 The event Object 503 13.7.3 Using Event Object Properties The srcElement/target and type Properties. The srcElement (Internet Explorer) and the target properties (Firefox) return the element that fired the event. The srcEle- ment also has a tagName property: event.srcElement.tagName will return “IMG” if you click on an image object. And we can also read styles, so if the image has a style height of 100px, then event.srcElement.style.height will return “100px”. The type property contains the event name (e.g., click, mouseover, keypress, and so on). This is the same for nonphysical events. If we capture and handle an onload event, type will be “load”, and so on. target The node from which the event originated. timestamp Returns the time (in milliseconds since the epoch) the event was created. Not all events return a timestamp. type A string indicating the type of event, such as “mouseover”, “click”, and so on. which Netscape legacy property indicating the Unicode for the key pressed. Identical to charCode. modifiers The bitmask representing modifier keys such as Alt, Shift, Meta, and so on. data Array of URLs for dragged and dropped. height and width Height and width of the window. EXAMPLE 13.21 <html> <head><title>Event Properties</title></head> <body bgcolor="yellow" <! Internet Explorer has srcElement property > <! Firefox has target property > <! Opera has both > 1 <form name="form1"> 2 <input type=button value="Internet Explorer" 3 onClick="alert( event.type + ' ' + event.srcElement);"> <input type=button value="Firefox" 4 onClick="alert( event.type + ' ' + event.target);" /> Continues Table 13.9 Properties of the event Object: Mozilla Firefox (continued) Property What It Describes From the Library of WoweBook.Com ptg 504 Chapter 13 • Handling Events </form> </body> </html> EXPLANATION 1 The HTML form starts here. 2 When the user clicks the first button in this form, the onClick event is triggered. It will cause an alert message to appear displaying two event properties: the type of the event and the HTML element where it came from (srcElement (Internet Ex- plorer) property of the object). The type of event is cross-browser compliant. 3 The input type for this form is a button. When the user clicks the button for In- ternet Explorer, an alert box displays the type of the event and the source or object from when it originated. 4 When the onClick event is triggered, an alert message will appear displaying two event properties: the type of the event and the target (Firefox) property or object from which the event originated. See Figures 13.30, 13.31, and 13.32. W3C and Firefox both use the target property. Internet Explorer uses srcElement. Figure 13.30 Displaying the event object’s property in Internet Explorer (left), and Firefox (right). Figure 13.31 The user clicked the Firefox button. EXAMPLE 13.21 (CONTINUED) From the Library of WoweBook.Com ptg 13.7 The event Object 505 13.7.4 Passing Events to a JavaScript Function As stated earlier, JavaScript registers events as they occur within the document and reg- isters information about that event such as what key was pressed, what mouse button clicked, and so on. You can pass this information directly to a JavaScript function. The problem is that Internet Explorer has its own way of tracking events and the other major browsers use the W3C standard (e.g., Firefox and Opera). With the W3C method, the event object is sent as a parameter to the JavaScript function, but with Internet Explorer the event is a property of the window object (window.event). It is easy enough to check for both without interrupting the flow of your program by testing for both conditions. The following line uses the ternary operator to test for both events and for null. (The ternary operator was described in detail in section “The Conditional Operator” on page 108, Chapter 5.) function testEvent(e){ var evt = (e) ? e: ((window.event)? window.event: null) } Figure 13.32 The user clicked the Internet Explorer button. EXAMPLE 13.22 <html> <head><title>Event Object and Incompatible Browsers</title> <script> 1 function whichEvent(e) { // passing e is for Firefox 2 if(!e){ var e=window.event;} // Microsoft IE Continues From the Library of WoweBook.Com ptg 506 Chapter 13 • Handling Events 3 if(e.target){targ=e.currentTarget; targ=targ.id;} // Firefox 4 else if(e.srcElement){targ=e.srcElement.id;} // Microsoft IE 5 alert(targ +" has recieved a "+e.type); } </script> </head> 6 <body id="main" onload="whichEvent(event);"> <br /> 7 <div style="background-color:lightgreen"> <form id="form1" onclick="whichEvent(event);"> <br /> <input type="text" id="textbox1" onkeypress="whichEvent(event);" /> <br /><br /> <input type="button" value="rollover me" id="button1" onmouseout="whichEvent(event);" /> <br /> </form> </div> </body> </html> EXPLANATION 1 Four types of events will be sent to this user-defined function: the load, keypress, mouseout, and click events. The purpose of the function is to show you how to make a cross-compliant script to handle events on different browsers. 2 Unless the browser is Microsoft Internet Explorer, a reference to the event object is passed as an argument to whichEvent() and called e as a parameter to the which- Event() function. If not, Internet Explorer uses the event property of the window object to get the value of e. 3 If the target property is applied to the object, then a Mozilla type browser is being used. The currentTarget property returns the object from where the click originat- ed. (To understand the flow of events, see the section “Capturing and Bubbling (Trickle Down and Bubble Up)” on page 500.) Using the id attribute of the object where the event occurs allows us to identify what object received the event. For example, if the user clicks the form, with the id of form1, then we can see that the click originated in form1. 4 If the srcElement property is defined, then we are using Internet Explorer 5 The id of the element and the type of event that was fired are displayed. 6 When the page has loaded, the user-defined function, whichEvent, is triggered. If this is a Mozilla type browser, the event object is passed to the function. EXAMPLE 13.22 (CONTINUED) From the Library of WoweBook.Com ptg 13.7 The event Object 507 7 Each object, the form, the textbox, and the button have an event attribute that will be triggered if the user clicks any of those objects. The argument to this function, event, is a reference to the particular event that was triggered when the user clicked it. Output examples are shown in Figures 13.33, 13.34, 13.35, and 13.36. Figure 13.33 Opera—the mouse has left the button. Figure 13.34 Microsoft IE—The mouse was clicked in the textbox—bubble up. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 508 Chapter 13 • Handling Events 13.7.5 Mouse Positions We devoted a whole section of this chapter to handling mouse event handlers and what hap- pens if the mouse rolls over a link or an image. In this section we discuss how to find out what event the mouse triggered and where the mouse was positioned when it fired. For browser compatibility tables see http://www.quirksmode.org/dom/w3c_cssom.html. Mouse Position. The client X and clientY properties (Internet Explorer) and pageX and pageY properties (Firefox) are used to get the coordinate positions of the mouse pointer in the document when the event is triggered. If you want to get the coordinate positions of the mouse within an element, then you would use the offsetX and offsetY properties (Internet Explorer) and nonstandard layerX and layerY (Firefox). Figure 13.35 Firefox—The mouse was clicked in the textbox but captured first in the form. Figure 13.36 Firefox—A key was pressed in the textbox. From the Library of WoweBook.Com . the time with JavaScript. Event objects are sent to an event handler with each event that occurs within a docu- ment; for example, when the user clicks on the left mouse button, JavaScript registers. WoweBook.Com ptg 13.7 The event Object 505 13.7.4 Passing Events to a JavaScript Function As stated earlier, JavaScript registers events as they occur within the document and reg- isters information about that event. in this chapter pro- vides the JavaScript code for testing. We discuss bubbling and capturing again in Chap- ter 15. Figure 13.29 Bubbling and capturing. window document form button Capturing

Ngày đăng: 04/07/2014, 02:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan