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

JavaScript Bible, Gold Edition part 37 pot

10 240 0

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

THÔNG TIN TÀI LIỆU

Nội dung

208 Part III ✦ Document Objects Reference Day: <INPUT Name=”day” Type=”text” Size=”3” VALUE=”” onKeyUp =”jumpNext(this, year)” maxLength=”2”> Year: <INPUT Name=”year” Type=”text” Size=”3” VALUE=”” onKeyUp =”jumpNext(this, month)” maxLength=”2”> </FORM> </BODY> </HTML> These three events do not fire for all keys of the typical PC keyboard on all browser versions that support keyboard events. The only keys that you can rely on supporting the events in all browsers shown in the preceding compatibility chart are the alphanumeric keys represented by ASCII values. This includes keys such as the spacebar and Enter (Return on the Mac), but it excludes all function keys, arrow keys, and other navigation keys. Modifier keys, such as Shift, Ctrl (PC), Alt (PC), Command (Mac), and Option (Mac), generate some events on their own (depending on browser and version). However, functions invoked by other key events can always inspect the pressed states of these modifier keys. Scripting keyboard events almost always entails examining which key is pressed so that some processing or validation can be performed on that key press. This is where the situation gets very complex if you are writing for cross-browser imple- mentation. In some cases, even writing just for Internet Explorer gets tricky because non-alphanumeric keys generate only the onKeyDown and onKeyUp events. In fact, to fully comprehend keyboard events, you need to make a distinction between key codes and character codes. Every PC keyboard key has a key code asso- ciated with it. This key code is always the same regardless of what other keys you press at the same time. Only the alphanumeric keys (letters, numbers, spacebar, and so on), however, generate character codes. The code represents the typed character produced by that key. The value might change if you press a modifier key. For example, if you type the “A” key by itself, it generates a lowercase “a” character (character code 97); if you also hold down the Shift key, that same key produces an uppercase “A” character (character code 65). The key code for that key (65 for Western language keyboards) remains the same no matter what. That brings us, then, to where these different codes are made available to scripts. In all cases, the code information is conveyed as one or two properties of the browser’s event object. IE’s event object has only one such property — keyCode. It contains key codes for onKeyDown and onKeyUp events, but character codes for onKeyPress events. The NN6 event object, on the other hand, contains two separate properties: charCode and keyCode. You can find more details and examples about these event object properties in Chapter 29. The bottom-line script consideration is to use either onKeyDown or onKeyUp event handlers when you want to look for non-alphanumeric key events (for example, func- tion keys, arrow and page navigation keys, and so on). To process characters as they appear in text boxes, use the onKeyPress event handler. You can experiment with these events and codes in Listing 15-41 as well as in examples from Chapter 29. Common keyboard event tasks IE4+ (but not NN) enables you to modify the character that a user who is editing a text box enters. The onKeyPress event handler can modify the event.keyCode property and allow the event to continue (in other words, don’t evaluate to return false or set the event.returnValue property to false). The following IE elementObject.onKeyDown 209 Chapter 15 ✦ Generic HTML Element Objects function (invoked by an onKeyPress event handler) makes sure text entered into a text field is all uppercase, even if you type it as lowercase: function assureUpper() { if (event.charCode >= 97 && event.charCode <= 122) { event.charCode = event.charCode - 32 } } Doing this might confuse (or frustrate) users, so think carefully before imple- menting such a plan. To prevent a keyboard key press from becoming a typed character in a text field, the onKeyPress event handler prevents the default action of the event. For exam- ple, the following (NN4+, IE4+) HTML page shows how to inspect a text field’s entry for numbers only: <HTML> <HEAD> <TITLE>Keyboard Capture</TITLE> <SCRIPT LANGUAGE=”JavaScript”> function checkIt(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) { alert(“Please make sure entries are numbers only.”) return false } return true } </SCRIPT> </HEAD> <BODY> <FORM> Enter any positive integer: <INPUT TYPE=”text” NAME=”numeric” onKeyPress=”return checkIt(event)”> </FORM> </BODY> </HTML> Whenever a user enters a non-number, the user receives a warning and the char- acter is not appended to the text box’s text. Keyboard events also enable you to script the submission of a form when a user presses the Enter (Return on the Mac) key within a text box. The ASCII value of the Enter/Return key is 13. Therefore, you can examine each key press in a text box and submit the form whenever value 13 arrives, as shown in the following function, which works in IE4+ and NN4+: function checkForEnter(evt) { evt = (evt) ? evt : event var charCode = (evt.which) ? evt.which : evt.keyCode if (charCode == 13) { document.forms[0].submit() return false } return true } elementObject.onKeyDown 210 Part III ✦ Document Objects Reference By assigning the checkForEnter() function to each field’s onKeyPress event handler, you suddenly add some extra power to a typical HTML form. You can intercept Ctrl+keyboard combinations (letters only) in HTML pages most effectively in Internet Explorer, but only if the browser itself does not use the combination. In other words, you cannot redirect Ctrl+key combinations that the browser uses for its own control. The onKeyPress keyCode value for Ctrl+combina- tions ranges from 1 through 26 for letters A through Z (except for those used by the browser, in which case no keyboard event fires). Example (with Listing 15-41) on the CD-ROM Related Item: String.fromCharCode() method. onLoseCapture NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ The onLoseCapture event handler fires whenever an object that has event capture turned on no longer has that capture. Event capture is automatically disengaged when the user performs any of the following actions: ✦ Gives focus to any other window ✦ Displays any system modal dialog box (for example, alert window) ✦ Scrolls the page ✦ Opens a browser context menu (right-clicking) ✦ Tabs to give focus to the Address field in the browser window A function associated with the onLoseCapture event handler should perform any cleanup of the environment due to an object no longer capturing mouse events. Example on the CD-ROM Related Items: releaseCapture(), setCapture() methods. On the CD-ROM On the CD-ROM elementObject.onLoseCapture 211 Chapter 15 ✦ Generic HTML Element Objects onMouseDown onMouseUp NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓✓✓ The onMouseDown event handler fires when the user presses any button of a mouse. The onMouseUp event handler fires when the user releases the mouse but- ton, provided the object receiving the event also received an onMouseDown event. When a user performs a typical click of the mouse button atop an object, mouse events occur in the following sequence: onMouseDown, onMouseUp, onClick. But if the user presses the mouse atop an object and then slides the cursor away from the object, only the onMouseDown event fires. In NN4, these two mouse events were limited to button, radio button, checkbox, link, and area objects. These events enable authors and designers to add more application-like behav- ior to images that act as action or icon buttons. If you notice the way most buttons work, the appearance of the button changes while you press the mouse button and reverts to its original style when you release the mouse button (or you drag the cursor out of the button). These events enable you to emulate that behavior. The event object created with every mouse button action has a property that reveals which mouse button the user pressed. NN4’s event model calls that prop- erty the which property. IE4+ and NN6 call it the button property (but with differ- ent values for the buttons). It is most reliable to test for the mouse button number on either the onMouseDown or onMouseUp event, rather than on onClick. The onClick event object does not always contain the button information. Example (with Listing 15-42) on the CD-ROM Related Item: onClick event handler. onMouseEnter onMouseLeave NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Two event handlers that are new with IE5.5 are onMouseEnter and onMouseLeave. Both event handlers operate just like the onMouseOver and onMouseOut event handlers, respectively. Microsoft simply offers an alternate ter- minology. The old and new events continue to fire in IE5.5. The old ones fire just before the new ones for each act of moving the cursor atop, and exiting from atop, the object. If you are scripting exclusively for IE5.5+, then you should use the new terminology; otherwise, stay with the older versions. On the CD-ROM elementObject.onMouseEnter 212 Part III ✦ Document Objects Reference Example on the CD-ROM Related Items: onMouseOver, onMouseOut event handlers. onMouseMove NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility (✓) ✓✓✓✓ The onMouseMove event handler fires whenever the cursor is atop the current object and the mouse is moved, even by a single pixel. You do not have to press the mouse button for the event to fire, although the event is most commonly used in element dragging — especially in NN, where no onDrag event handler is available. Even though the granularity of this event can be at the pixel level, you should not use the number of event firings as a measurement device. Depending on the speed of cursor motion and the performance of the client computer, the event may not fire at every pixel location. In NN4, you cannot assign the onMouseMove event handler to any object by way of tag attributes. But you can use the NN4 event capturing mechanism to instruct (via scripting) a window, document, or layer object to capture mouseMove events. This allows for NN4 scripts to produce positioned element (layer) dragging. In IE4+ and NN6+, however, you can assign the onMouseMove event handler to any element (although you can drag only with positioned elements). When designing a page that encourages users to drag multiple items on a page, it is most common to assign the onMouseMove event handler to the document object and let all such events bubble up to the document for processing. Example (with Listing 15-43) on the CD-ROM Related Items: onDrag, onMouseDown, onMouseUp event handlers. onMouseOut onMouseOver NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓ ✓ ✓ ✓ ✓✓ ✓ The onMouseOver event fires for an object whenever the cursor rolls into the rectangular space of the object on the screen (one event per entry into the object — except for a bug in NN4/Windows, which causes the onMouseOver event On the CD-ROM On the CD-ROM elementObject.onMouseOut 213 Chapter 15 ✦ Generic HTML Element Objects to fire with mouse movement). The onMouseOut event handler fires when you move the cursor outside the object’s rectangle. These events most commonly display explanatory text about an object in the window’s status bar and effect image swap- ping (so-called mouse rollovers). Use the onMouseOver event handler to change the state to a highlighted version; use the onMouseOut event handler to restore the image or status bar to its normal setting. While these two events have been in object models of scriptable browsers since the beginning, they were not available to most objects in earlier browsers. The onMouseOver event was available only to the link object until the version 4 browsers. Even then, NN4 still restricted this event to link, area, and layer objects. The onMouseOut event handler first surfaced for link and area objects in Navigator 3. IE4+ and NN6+ provide support for these events on every element that occupies space on the screen. IE5.5 includes an additional pair of event handlers — onMouseEnter and onMouseLeave — that duplicate the onMouseOver and onMouseOut events but with different terminology. The old event handlers fire just before the new versions. The onMouseOut event handler commonly fails to fire if the event is associated with an element that is near a frame or window edge and the user moves the cursor quickly outside of the current frame. Example (with Listing 15-44) on the CD-ROM Related Items: onMouseEnter, onMouseLeave, onMouseMove event handlers. onPaste NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ The onPaste event (not implemented in IE5/Mac) fires immediately after the user or script initiates a paste edit action on the current object. The event is pre- ceded by the onBeforePaste event, which fires prior to any edit or context menu that appears (or before the paste action if initiated by keyboard shortcut). Use this event handler to provide edit functionality to elements that don’t normally allow pasting. In such circumstances, you need to enable the Paste menu item in the context or Edit menu by setting the event.returnValue for the onBeforePaste event handler to false. Then your onPaste event handler must manually retrieve data from the clipboard (by way of the getData() method of the clipboardData object) and handle the insertion into the current object. Because you are in charge of what data is stored in the clipboard, you are not limited to a direct copy of the data. For example, you might wish to store the value of the src property of an image object so that you can paste it elsewhere on the page. On the CD-ROM Note elementObject.onPaste 214 Part III ✦ Document Objects Reference Example (with Listing 15-45) on the CD-ROM Related Items: onCopy, onCut, onBeforePaste event handlers. onPropertyChange NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ The onPropertyChange event fires in Windows versions of IE5+ whenever a script modifies an object’s property. This includes changes to the properties of an object’s style. Changing properties by way of the setAttribute() method also triggers this event. A script can inspect the nature of the property change because the event.propertyName property contains the name (as a string) of the property that was just changed. In the case of a change to an object’s style object, the event. propertyName value begins with “style.” as in style.backgroundcolor. You can use this event handler to localize any object-specific post-processing of changes to an object’s properties. Rather than include the post-processing state- ments inside the function that makes the changes, you can make that function generalized (perhaps to modify properties of multiple objects). Example (with Listing 15-46) on the CD-ROM Related Items: style property; setAttribute() method. onReadyStateChange NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓ The onReadyStateChange event handler fires whenever the ready state of an object changes. See details about these states in the discussion of the readyState property earlier in this chapter (and notice the limits for IE4). The change of state does not guarantee that an object is, in fact, ready for script statements to access its properties. Always check the readyState property of the object in any script that the onReadyStateChange event handler invokes. This event fires for objects that are capable of loading data: APPLET, document, FRAME, FRAMESET, IFRAME, IMG, LINK, OBJECT, SCRIPT, and XML objects. The event doesn’t fire for other types of objects unless a Microsoft DHTML behavior is associated with the object. The onReadyStateChange event does not bubble, nor can you cancel it. On the CD-ROM On the CD-ROM elementObject.onReadyStateChange 215 Chapter 15 ✦ Generic HTML Element Objects Example on the CD-ROM Related Item: readyState property. onResize NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓✓✓ The onResize event handler fires whenever an object is resized in response to a variety of user or scripted actions. In NN4+, the onResize event handler is avail- able only for the window object; IE4 includes this event handler for the APPLET, AREA, BUTTON, DIV, FIELDSET, FRAMESET, IMG, MARQUEE, SELECT, TABLE, TD, TH, and window objects. Virtually every content-containing element in IE5+ has this event handler, provided the object has dimensional style attributes (for example, height, width, or position) assigned to it. Window resizing presents potentially serious problems in NN4, especially when the page contains positioned elements. Unlike IE4+ and NN6, the NN4 rendering engine typically fails to redraw a resized page properly. A reload of the page usually fixes the problems. You can use the onResize event handler in NN4 to repair the damage: window.onresize = restorePage function restorePage() { history.go(0) } But there is one additional complication in NN4 for Windows when the content of a window or frame requires scrollbars. The application of the scrollbars forces another resize event. In concert with the preceding code, the page gets in an infinite loop of reloading the page. To guard against this, your script must compare the innerWidth and innerHeight of the window before and after the resize event: var Nav4 = ((navigator.appName == “Netscape”)&& (parseInt(navigator.appVersion) == 4)) window.onresize = restorePage if (Nav4) { var startWidth = window.innerWidth var startHeight = window.innerHeight } function restorePage() { if (Nav4) { if (startWidth != window.innerWidth|| startHeight != window.innerHeight) { history.go(0) } } } On the CD-ROM elementObject.onResize 216 Part III ✦ Document Objects Reference In IE4+ and NN6, the onResize event does not bubble. Resizing the browser window or frame does not cause the window’s onLoad event handler to fire. Example on the CD-ROM Related Item: window.resize() method. onResizeEnd onResizeStart NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ The onResizeEnd and onResizeStart event handlers fire only on a resizable object in Windows edit mode. As mentioned in the discussion of the onControlSelect event handler, an authoritative description or example is not available yet. Related Item: onControlSelect event handler. onSelectStart NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓ The onSelectStart event handler fires when a user begins to select content on the page. Selected content can be inline text, images, or text within an editable text field. If the user selects more than one object, the event fires in the first object affected by the selection. Example (with Listing 15-47) on the CD-ROM Related Item: onSelect event handler for a variety of objects ✦✦✦ On the CD-ROM On the CD-ROM elementObject.onSelectStart Window and Frame Objects A quick look at the basic document object model diagram in Chapter 14 (Figure 14-1) reveals that the window object is the outermost, most global container of all docu- ment-related objects that you script with JavaScript. All HTML and JavaScript activity takes place inside a window. That win- dow may be a standard Windows, Mac, or Xwindows applica- tion-style window, complete with scrollbars, toolbars, and other “chrome;” you can also generate windows that have only some of a typical window’s chrome. A frame is also a window, even though a frame doesn’t have many accou- trements beyond scrollbars. The window object is where everything begins in JavaScript references to object. IE4+ and NN6 treat the frameset as a special kind of window object, so that it is also covered in this chapter. Of all the objects associated with browser scripting, the window and window-related objects have by far the most object-specific terminology associated with them. This necessitates a rather long chapter to keep the discussion in one place. Use the running footers as a navigational aid through this substantial collection of information. Window Terminology The window object is often a source of confusion when you first learn about the document object model. A number of syn- onyms for window objects muck up the works: top, self, parent, and frame. Aggravating the situation is that these terms are also properties of a window object. Under some con- ditions, a window is its own parent, but if you define a frame- set with two frames, you have only one parent among a total of three window objects. It doesn’t take long before the whole subject can make your head hurt. If you do not use frames in your Web applications, all of these headaches never appear. But if frames are part of your design plan, you should get to know how frames affect the object model. 16 16 CHAPTER ✦✦✦✦ In This Chapter Scripting communication among multiple frames Creating and managing new windows Controlling the size, position, and appearance of the browser window Details of Window, FRAME, FRAMESET, and IFRAME objects ✦✦✦✦ . outermost, most global container of all docu- ment-related objects that you script with JavaScript. All HTML and JavaScript activity takes place inside a window. That win- dow may be a standard Windows,. only: <HTML> <HEAD> <TITLE>Keyboard Capture</TITLE> <SCRIPT LANGUAGE= JavaScript > function checkIt(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if. (charCode == 13) { document.forms[0].submit() return false } return true } elementObject.onKeyDown 210 Part III ✦ Document Objects Reference By assigning the checkForEnter() function to each field’s

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