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

JavaScript Bible, Gold Edition part 45 pps

10 225 0

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

THÔNG TIN TÀI LIỆU

Nội dung

288 Part III ✦ Document Objects Reference showModalDialog(“URL”[, arguments] [, features]) showModelessDialog(“URL”[, arguments] [, features]) Returns: returnValue (modal) or window object (modeless). NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility (✓) ✓✓ IE4+ provides methods for opening a modal dialog box window, which always stays in front of the main browser window while making the main window inaccessi- ble to the user. In IE5 (but not IE5/Mac), Microsoft added the modeless type of dialog box, which also stays in front, but allows user access to whatever can be seen in the main window. You can load any HTML page or image that you like into the dialog box window, by providing a URL as the first parameter. Optional parameters let you pass data to a dialog box and give you considerable control over the look of the window. Unfortunately, these types of dialog box windows are not available in Navigator. At best, you can simulate modal and modeless dialog box windows, but the job is not for beginners (see http://developer.netscape.com/viewsource/ goodman_modal/goodman_modal.html for one example). The windows generated by both methods are (almost) full-fledged window objects with some extra properties that are useful for what these windows are intended to do. Perhaps the most important property is the window.dialogArgument property. This property lets a script read the data that is passed to the window via the second parameter of both showModalDialog() and showModelessDialog(). Passed data can be in any valid JavaScript data type, including objects and arrays. Displaying a modal dialog box has some ramifications for scripts. In particular, script execution in the main window halts at the statement that invokes the showModalDialog() method as long as the modal dialog box remains visible. Scripts are free to run in the dialog box window during this time. The instant the user closes the dialog box, execution resumes in the main window. A call to show a modeless dialog box, on the other hand, does not halt processing because scripts in the main page or dialog box window are allowed to communicate “live” with the other window. Retrieving dialog data To send data back to the main window’s script from a modal dialog box window, a script in the dialog box window can set the window.returnValue property to any JavaScript value. It is this value that gets assigned to the variable receiving the returned value from the setModelDialog() method, as shown in the following example: var specifications = window.showModalDialog(“preferences.html”) windowObject.showModalDialog() 289 Chapter 16 ✦ Window and Frame Objects The makeup and content of the returned data is in the hands of your scripts. No data is automatically returned for you. Because a modeless dialog box coexists with your live main page window, return- ing data is not as straightforward as for a modal dialog box. The second parameter of the showModelessDialog() method takes on a special task that isn’t exactly the same as passing parameters to the dialog box. Instead, if you define a global vari- able or a function in the main window’s script, pass a reference to that variable or function as the second parameter to display the modeless dialog box. A script in the modeless dialog box can then point to that reference as the way to send data back to the main window before the dialog box closes (or when a user clicks some- thing, such as an Apply button). This mechanism even allows for passing data back to a function in the main window. For example, say that the main window has a function defined as the following: function receivePrefsDialogData(a, b, c) { // statements to process incoming values // } Then pass a reference to this function when opening the window: dlog = showModelessDialog(“prefs.html”, receivePrefsDialogData) A script statement in the dialog box window’s document can pick up that refer- ence so that other statements can use it, such as a function for an Apply button’s onClick event handler: var returnFunc = window.dialogArguments function apply(form) { returnFunc(form.color.value, form.style.value, form.size.value) } While this approach seems to block ways of getting parameters to the dialog box when it opens, you can always reference the dialog box in the main window’s script and set form or variable values directly: dlog = showModelessDialog(“prefs.html”, receivePrefsDialogData) dlog.document.forms[0].userName.value = GetCookie(“userName”) Be aware that a dialog box window opened with either of these methods does not maintain a connection to the originating window via the opener property. The opener property for both dialog box types is undefined. Dialog window features Both methods provide an optional third property that lets you specify visible features of the dialog box window. Omitting the property sets all features to their default values. All parameters are to be contained by a single string, and each parameter’s name-value pair is in the form of CSS attribute:value syntax. Table 16-4 lists all of the window features available for the two window styles. If you are designing for compatibility with IE4, you are restricted to the modal dialog box and a subset of features, as noted in the table. All values listed as Boolean take only the following four values: yes, no, 1, 0. windowObject.showModalDialog() 290 Part III ✦ Document Objects Reference Table 16-4 IE Dialog Box Window Features Feature Type Default Description center Boolean yes Whether to center dialog box (overridden by dialogLeft and/or dialogTop). dialogHeight Length varies Outer height of the dialog box window. IE4 default length unit is em; IE5 is pixel (px). dialogLeft Integer varies Pixel offset of dialog box from left edge of screen. dialogTop Integer varies Pixel offset of dialog box from top edge of screen. dialogWidth Length varies Outer width of the dialog box window. IE4 default length unit is em; IE5 is pixel (px). help Boolean yes Display Help icon in title bar. resizable Boolean no Dialog box is resizable (IE5+ only). status Boolean varies Display statusbar at window bottom (IE5+ only). Default is yes for untrusted dialog box; no for trusted dialog box. The CSS-type of syntax for these features lets you string multiple features together by separating each pair with a semicolon within the string. For example: var dlogData = showModalDialog(“prefs.html”, defaultData, “dialogHeight:300px; dialogWidth:460px; help:no”) Although not explicitly listed as one of the window features, scroll bars are nor- mally displayed in the window if the content exceeds the size assigned or available to the dialog box. If you don’t want scroll bars to appear, have your dialog box docu- ment’s script set the document.body.scroll property to false as the page opens. Dialog cautions A potential user problem to watch for is that typically a dialog box window does not open until the HTML file for the dialog box has loaded. Therefore, if there is substantial delay before a complex document loads, the user does not see any action indicating that something is happening. You may want to experiment with setting the cursor style sheet property and restoring it when the dialog box’s document loads. windowObject.showModalDialog() 291 Chapter 16 ✦ Window and Frame Objects One of the reasons I call a dialog box window an (almost) window object is that some normal behavior is not available in IE4. For example, if you load a frameset into the dialog box window, scripts in documents within the frames cannot refer back to the parent document to access variables or parent window methods. Thus, a button in a frame of an IE4 modal dialog box cannot issue parent.close() to close the dialog box. This anomaly is repaired in IE5. Example (with Listings 16-39 through 16-42) on the CD-ROM Related Items: window.open() method. sizeToContent() Returns: Nothing. NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ The NN6 window.sizeToContent() method can be a valuable aid in making sure that a window (especially a subwindow) is sized for the optimum display of the window’s content. But you must also be cautious with this method, or it will do more harm than good. Invoking the sizeToContent() method resizes the window so that all content is visible. Concerns about variations in OS-specific rendering become a thing of the past. Naturally, you should perform this action only on a window whose content at the most occupies a space smaller than the smallest video monitor running your code (typically 640 × 480 pixels, but conceivably much smaller for future versions of the browser used on handheld computers). You can get the user in trouble, however, if you invoke the method twice on the same window that contains the resizing script. This action can cause the window to expand to a size that may exceed the pixel size of the user’s video monitor. Successive invocations fail to cinch up the window’s size to its content again. Multiple invocations are safe, however, on subwindows when the resizing script statement is in the main window. Example on the CD-ROM Related Item: window.resizeTo() method. On the CD-ROM On the CD-ROM windowObject.sizeToContent() 292 Part III ✦ Document Objects Reference stop() Returns: Nothing. NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ The Navigator-specific stop() method offers a scripted equivalent of clicking the Stop button in the toolbar. Availability of this method allows you to create your own toolbar on your page and hide the toolbar (in the main window with signed scripts or in a subwindow). For example, if you have an image representing the Stop button in your page, you can surround it with a link whose action stops loading, as in the following: <A HREF=”javascript: void stop()”><IMG SRC=”myStop.gif” BORDER=0></A> A script cannot stop its own document from loading, but it can stop loading of another frame or window. Similarly, if the current document dynamically loads a new image or a multimedia MIME type file as a separate action, the stop() method can halt that process. Even though the stop() method is a window method, it is not tied to any specific window or frame: Stop means stop. Related Items: window.back(), window.find(), window.forward(), window.home(), window.print() methods. Event handlers onAfterPrint onBeforePrint NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ Each of these event handlers (not implemented in IE5/Mac) fires after the user has clicked the OK button in IE’s Print dialog box. This goes for printing that is invoked manually (via menus and browser shortcut buttons) and the window.print() method. Although printing is usually WYSIWYG, it is conceivable that you may want the printed version of a document to display more or less of the document than is showing at that instant. For example, you may have a special copyright notice that you want printed at the end of a page whenever it goes to the printer. In that case, the element with that content can have its display style sheet property set to none when the page loads. Before the document is sent to the printer, a script needs to adjust that style property to display the element as a block item; after printing, have your script revert the setting to none. windowObject.onAfterPrint 293 Chapter 16 ✦ Window and Frame Objects Immediately after the user clicks the OK button in the Print dialog box, the onBeforePrint event handler fires. As soon as the page(s) is sent to the printer or spooler, the onAfterPrint event handler fires. Example on the CD-ROM onBeforeUnload NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ Any user or scripted action that normally forces the current page to be unloaded or replaced causes the onBeforeUnload event handler to fire (not implemented in IE5/Mac). Unlike the onUnload event handler, however, onBeforeUnload is a bit better behaved when it comes to allowing complex scripts to finish before the actual unloading takes place. Moreover, you can assign a string value to the event. returnValue property in the event handler function. That string becomes part of a message in an alert window that gives the user a chance to stay on the page. If the user agrees to stay, the page does not unload, and any action that caused the potential replacement is cancelled. Example (with Listing 16-43) on the CD-ROM Related Items: onUnload event handler. onDragDrop NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ With closer integration between the computer desktop and browsers these days, it is increasingly possible that shortcuts (or aliases) to Web URLs can be repre- sented on our desktops and other kinds of documents. With NN4, you can script awareness of dragging and dropping of such items onto the browser window. The window’s dragDrop event fires whenever a user drops a file or other URL-filled object onto the window. You can add an onDragDrop event handler to the <BODY> tag of your document and pass along the event object that has some juicy tidbits about the drop: the object on which the item was dropped and the URL of the item. The function called by the event handler receives the event object information and can process it from On the CD-ROM On the CD-ROM windowObject.onDragDrop 294 Part III ✦ Document Objects Reference there. Because this event is a window event, you don’t have to turn on window.captureEvents() to get the window to feel the effect of the event. The juiciest tidbit of the event, the URL of the dropped item, can be retrieved only with a signed script and the user’s permission (see Chapter 46). Listing 16-44 shows a simple document that reveals the URL and screen location, as derived from the event object passed with the dragDrop event. You must have codebase princi- pals turned on to get the full advantage of this listing, and it works best with Windows. Listing 16-44: Analyzing a dragDrop Event <HTML> <HEAD> <TITLE>DragDrop Event</TITLE> <SCRIPT LANGUAGE=”JavaScript”> function reportDrag(e) { var msg = “You dropped the file:\n” netscape.security.PrivilegeManager.enablePrivilege(“UniversalBrowserRead”) msg += e.data netscape.security.PrivilegeManager.disablePrivilege(“UniversalBrowserRead”) msg += “\nonto the window object at screen location (“ msg += e.screenX + “,” + e.screenY + “).” alert(msg) return false } </SCRIPT> </HEAD> <BODY onDragDrop=”return reportDrag(event)”> <B>Drag and Drop a file onto this window</B> </BODY> </HTML> The dragDrop event is the only one that uses the data property of the NN4 event object. That property contains the URL. The target property reveals only the window object, but you can access the event object’s screenX and screenY properties to get the location of the mouse release. Related Items: event object (Chapter 29). onError NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓✓✓ See the discussion of the window.onerror property earlier in this chapter. windowObject.onError 295 Chapter 16 ✦ Window and Frame Objects onHelp NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ The generic onHelp event handler is discussed in Chapter 15, but it also fires when the user activates the context-sensitive help within a modal or modeless dia- log box. In the latter case, a user can click the Help icon in the dialog box’s title bar, at which time the cursor changes to a question mark. The user can then click on any element in the window. At that second click, the onHelp event handler fires, and the event object contains information about the element clicked (the event.srcElement is a reference to the specific element), allowing a script to supply help about that element. To prevent the brower’s built-in help window from appearing, the event handler must evaluate to return false (IE4+) or set the event.returnValue property to false (IE5). Example The following script fragment can be embedded in the IE5-only modeless dialog box code in Listing 16-44 to provide context-sensitive help within the dialog box. Help messages for only two of the form elements are shown here, but in a real appli- cation you add messages for the rest. function showHelp() { switch (event.srcElement.name) { case “bgColor” : alert(“Choose a color for the main window\’s background.”) break case “name” : alert(“Enter your first name for a friendly greeting.”) break default : alert(“Make preference settings for the main page styles.”) } event.returnValue = false } window.onhelp = showHelp Because this page’s help focuses on form elements, the switch construction cases are based on the name properties of the form elements. For other kinds of pages, the id properties may be more appropriate. Related Items: event object (Chapter 29); switch construction (Chapter 39). windowObject.onHelp 296 Part III ✦ Document Objects Reference onLoad NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓✓ ✓ ✓ ✓✓✓ The onLoad event handler fires in the current window at the end of the docu- ment loading process (after all text and image elements have been transferred from the source file server to the browser, and after all plug-ins and Java applets have loaded and started running). At that point, the browser’s memory contains all the objects and script components in the document that the browser can possibly know about. The onLoad handler is an attribute of a <BODY> tag for a single-frame document or of the <FRAMESET> tag for the top window of a multiple-frame document. When the handler is an attribute of a <FRAMESET> tag, the event triggers only after all frames defined by that frameset have completely loaded. Use either of the following scenarios to insert an onLoad handler into a document: <HTML> <HEAD> </HEAD> <BODY [other attributes] onLoad=”statementOrFunction”> [body content] </BODY> </HTML> <HTML> <HEAD> </HEAD> <FRAMESET [other attributes] onLoad=”statementOrFunction”> <FRAME>frame specifications</FRAME> </FRAMESET> </HTML> This handler has a special capability when part of a frameset definition: The han- dler won’t fire until the onLoad event handlers of all child frames in the frameset have fired. Therefore, if some initialization scripts depend on components existing in other frames, trigger them from the frameset’s onLoad event handler. This brings up a good general rule of thumb for writing JavaScript: Scripts that execute during a document’s loading should contribute to the process of generating the document and its objects. To act immediately on those objects, design additional functions that are called by the onLoad event handler for that window. The type of operations suited for an onLoad event handler are those that can run quickly and without user intervention. Users shouldn’t be penalized by having to wait for considerable post-loading activity to finish before they can interact with your pages. At no time should you present a modal dialog box as part of an onLoad handler. Users who design macros on their machines to visit sites unattended may get hung up on a page that automatically displays an alert, confirm, or prompt dia- log box. On the other hand, an operation such as setting the window.defaultStatus property is a perfect candidate for an onLoad event han- dler, as are initializing event handlers as properties of element objects in the page. windowObject.onload 297 Chapter 16 ✦ Window and Frame Objects Related Items: onUnload event handler; window.defaultStatus property. onMove NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ If a user drags an NN4 window around the screen, the action triggers a move event for the window object. When you assign a function to the event (for example, window.onmove = handleMoves), the function receives an event object whose screenX and screenY properties reveal the coordinate point (relative to the entire screen) of the top-left corner of the window after the move. Related Items: event object (Chapter 29). onResize NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ ✓✓✓ If a user resizes a window, the action causes the onResize event handler to fire for the window object. When you assign a function to the event (for example, window.onresize = handleResizes), the NN event object conveys width and height properties that reveal the outer width and height of the entire window. A window resize should not reload the document such that an onLoad event handler fires (although some early Navigator versions did fire the extra event). windowObject.onResize onLoad Bugs and Anomalies The onLoad event has changed its behavior over the life of JavaScript in Navigator. In Navigator 2, the onLoad event handler fired whenever the user resized the window. Many developers considered this a bug because the running of such scripts destroyed data that were carefully gathered since the document originally loaded. From Navigator 3 onward (and including IE3+), a window resize does not trigger a load event. Two onLoad bugs haunt Navigator 3 when used in conjunction with framesets. The first bug affects only Windows versions. The problem is that the frameset’s onLoad event handler is not necessarily the last one to fire among all the frames. It is possible that one frame’s onLoad event may still not have processed before the frameset’s onLoad event handler goes. This can cause serious problems if your frameset’s onLoad event handler relies on that final frame being fully loaded. The second bug affects all versions of NN3, but at least a workaround exists. If a frame con- tains a Java applet, the frameset’s onLoad event handler will fire before the applet has fully loaded and started. But if you place an onLoad event handler in the applet’s document (even a dummy onLoad=”” in the <BODY> tag), the frameset’s onLoad event handler behaves properly. . and showModelessDialog(). Passed data can be in any valid JavaScript data type, including objects and arrays. Displaying a modal dialog box has some ramifications for scripts. In particular, script execution in the. 288 Part III ✦ Document Objects Reference showModalDialog(“URL”[, arguments] [, features]) showModelessDialog(“URL”[,. dialog box window, a script in the dialog box window can set the window.returnValue property to any JavaScript value. It is this value that gets assigned to the variable receiving the returned value

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

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

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN