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

JavaScript Bible, Gold Edition part 45 pps

10 226 0
Tài liệu đã được kiểm tra trùng lặp

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 118,72 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 IE4+ provides methods for opening a modal dialog box window, which always stays in front of the main browser window while making the main wind

Trang 1

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

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.htmlfor 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.dialogArgumentproperty 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.returnValueproperty 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()

Trang 2

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 varivari-able 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

onClickevent 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 openerproperty The

openerproperty 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:valuesyntax 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()

Trang 3

Table 16-4 IE Dialog Box Window Features

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.scrollproperty to falseas 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 cursorstyle sheet property and restoring it when the dialog box’s document loads

windowObject.showModalDialog()

Trang 4

One of the reasons I call a dialog box window an (almost) windowobject 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

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()

Trang 5

Returns: Nothing.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

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

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 displaystyle sheet property set to

nonewhen 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

Trang 6

Immediately after the user clicks the OK button in the Print dialog box, the

onBeforePrintevent handler fires As soon as the page(s) is sent to the printer or

spooler, the onAfterPrintevent handler fires

Example on the CD-ROM

onBeforeUnload

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Any user or scripted action that normally forces the current page to be unloaded

or replaced causes the onBeforeUnloadevent handler to fire (not implemented in

IE5/Mac) Unlike the onUnloadevent handler, however, onBeforeUnloadis 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

returnValueproperty 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:onUnloadevent handler

onDragDrop

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

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 dragDropevent fires whenever a user drops a file or other URL-filled

object onto the window

You can add an onDragDropevent 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

Trang 7

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 dragDropevent 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 dragDropevent is the only one that uses the dataproperty of the NN4 event object That property contains the URL The targetproperty reveals only the windowobject, but you can access the event object’s screenXand screenY

properties to get the location of the mouse release

Related Items:eventobject (Chapter 29)

onError

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

See the discussion of the window.onerrorproperty earlier in this chapter

windowObject.onError

Trang 8

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

The generic onHelpevent 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 diadia-log 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 onHelpevent handler fires,

and the eventobject contains information about the element clicked (the

event.srcElementis 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.returnValueproperty 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 switchconstruction

cases are based on the nameproperties of the form elements For other kinds of

pages, the idproperties may be more appropriate

Related Items:eventobject (Chapter 29); switchconstruction (Chapter 39)

windowObject.onHelp

Trang 9

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

The onLoadevent handler fires in the current window at the end of the docu-ment loading process (after all text and image eledocu-ments 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 onLoadhandler 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 onLoadhandler 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 onLoadevent 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 onLoadevent 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 onLoadevent handler for that window

The type of operations suited for an onLoadevent 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.defaultStatusproperty is a perfect candidate for an onLoadevent han-dler, as are initializing event handlers as properties of element objects in the page

windowObject.onload

Trang 10

Related Items:onUnloadevent handler; window.defaultStatusproperty.

onMove

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

If a user drags an NN4 window around the screen, the action triggers a move

event for the windowobject When you assign a function to the event (for example,

window.onmove = handleMoves), the function receives an event object whose

screenXand screenYproperties reveal the coordinate point (relative to the entire

screen) of the top-left corner of the window after the move

Related Items:eventobject (Chapter 29)

onResize

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

If a user resizes a window, the action causes the onResizeevent handler to fire

for the windowobject When you assign a function to the event (for example,

window.onresize = handleResizes), the NN event object conveys widthand

heightproperties that reveal the outer width and height of the entire window A

window resize should not reload the document such that an onLoadevent 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 onLoadevent 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 onLoadbugs haunt Navigator 3 when used in conjunction with framesets The first bug

affects only Windows versions The problem is that the frameset’s onLoadevent handler is

not necessarily the last one to fire among all the frames It is possible that one frame’s

onLoadevent may still not have processed before the frameset’s onLoad event handler

goes This can cause serious problems if your frameset’s onLoadevent 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 onLoadevent handler will fire before the applet has fully

loaded and started But if you place an onLoadevent handler in the applet’s document

(even a dummy onLoad=”” in the <BODY> tag), the frameset’s onLoad event handler

behaves properly

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