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

JavaScript Bible, Gold Edition part 37 pot

10 241 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 196,17 KB

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

Nội dung

onLoseCapture NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 The onLoseCaptureevent handler fires whenever an object that has event capture turned on no longer has that capture.. Event capt

Trang 1

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 onKeyDownand onKeyUpevents

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 eventobject IE’s eventobject has only one such property —

keyCode It contains key codes for onKeyDownand onKeyUpevents, but character codes for onKeyPressevents The NN6 event object, on the other hand, contains two separate properties: charCodeand keyCode You can find more details and examples about these eventobject properties in Chapter 29

The bottom-line script consideration is to use either onKeyDownor onKeyUpevent handlers when you want to look for non-alphanumeric key events (for example, func-tion keys, arrow and page navigafunc-tion keys, and so on) To process characters as they appear in text boxes, use the onKeyPressevent 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 onKeyPressevent handler can modify the event.keyCode

property and allow the event to continue (in other words, don’t evaluate to return falseor set the event.returnValueproperty to false) The following IE

elementObject.onKeyDown

Trang 2

function (invoked by an onKeyPressevent 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 onKeyPressevent 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

Trang 3

By assigning the checkForEnter()function to each field’s onKeyPressevent 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 keyCodevalue 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

The onLoseCaptureevent 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 onLoseCaptureevent 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

Trang 4

onMouseUp

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

The onMouseDownevent handler fires when the user presses any button of a

mouse The onMouseUpevent handler fires when the user releases the mouse

but-ton, provided the object receiving the event also received an onMouseDownevent

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 onMouseDownevent fires In NN4, these two mouse events were

limited to button, radio button, checkbox, link, and areaobjects

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 whichproperty IE4+ and NN6 call it the buttonproperty (but with

differ-ent values for the buttons) It is most reliable to test for the mouse button number

on either the onMouseDownor onMouseUpevent, rather than on onClick The

onClickevent object does not always contain the button information

Example (with Listing 15-42) on the CD-ROM

Related Item:onClickevent handler

onMouseEnter

onMouseLeave

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

Two event handlers that are new with IE5.5 are onMouseEnterand

onMouseLeave Both event handlers operate just like the onMouseOverand

onMouseOutevent 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

Trang 5

Example on the CD-ROM

Related Items:onMouseOver, onMouseOutevent handlers

onMouseMove

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

The onMouseMoveevent 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 onDragevent 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 onMouseMoveevent 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 layerobject to capture mouseMoveevents This allows for NN4 scripts to produce positioned element (layer) dragging In IE4+ and NN6+, however, you can assign the onMouseMoveevent 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

onMouseMoveevent handler to the documentobject 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, onMouseUpevent handlers

onMouseOut

onMouseOver

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

The onMouseOverevent 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 onMouseOverevent

On the

CD-ROM

On the

CD-ROM

elementObject.onMouseOut

Trang 6

to fire with mouse movement) The onMouseOutevent 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 onMouseOverevent handler to change the

state to a highlighted version; use the onMouseOutevent 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

onMouseOverevent 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 onMouseOutevent 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 —

onMouseEnterand onMouseLeave— that duplicate the onMouseOverand

onMouseOutevents 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, onMouseMoveevent handlers

onPaste

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

The onPasteevent (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 onBeforePasteevent, 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.returnValuefor the

onBeforePasteevent handler to false Then your onPasteevent handler must

manually retrieve data from the clipboard (by way of the getData()method of the

clipboardDataobject) 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 srcproperty of an image object so that you can paste it elsewhere on the

page

On the

CD-ROM

Note

elementObject.onPaste

Trang 7

Example (with Listing 15-45) on the CD-ROM

Related Items:onCopy, onCut, onBeforePasteevent handlers

onPropertyChange

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

The onPropertyChangeevent 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.propertyNameproperty contains the name (as a string) of the property that was just changed In the case of a change to an object’s styleobject, the event propertyNamevalue 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:styleproperty; setAttribute()method

onReadyStateChange

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

The onReadyStateChangeevent 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 readyStateproperty of the object in any script that the onReadyStateChangeevent 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 onReadyStateChangeevent does not bubble, nor can you cancel it

On the

CD-ROM

On the

CD-ROM

elementObject.onReadyStateChange

Trang 8

Example on the CD-ROM

Related Item:readyStateproperty

onResize

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

The onResizeevent handler fires whenever an object is resized in response to a

variety of user or scripted actions In NN4+, the onResizeevent handler is

avail-able only for the windowobject; IE4 includes this event handler for the APPLET,

AREA, BUTTON, DIV, FIELDSET, FRAMESET, IMG, MARQUEE, SELECT, TABLE, TD,

TH, and windowobjects 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 onResizeevent 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

innerWidthand innerHeightof 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

Trang 9

In IE4+ and NN6, the onResizeevent does not bubble Resizing the browser window or frame does not cause the window’s onLoadevent 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

The onResizeEndand onResizeStartevent handlers fire only on a resizable object in Windows edit mode As mentioned in the discussion of the

onControlSelectevent handler, an authoritative description or example is not available yet

Related Item:onControlSelectevent handler

onSelectStart

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

The onSelectStartevent 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:onSelectevent handler for a variety of objects

On the

CD-ROM

On the

CD-ROM

elementObject.onSelectStart

Trang 10

Window and

Frame Objects

Aquick 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 Winwin-dows, Mac, or Xwinwin-dows

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 windowobject is where

everything begins in JavaScript references to object IE4+ and

NN6 treat the frameset as a special kind of windowobject, so

that it is also covered in this chapter

Of all the objects associated with browser scripting, the

windowand 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 windowobject is often a source of confusion when you

first learn about the document object model A number of

syn-onyms for windowobjects muck up the works: top, self,

parent, and frame Aggravating the situation is that these

terms are also properties of a windowobject 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 windowobjects 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

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

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