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

JavaScript Bible, Gold Edition part 35 doc

10 334 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 160,03 KB

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

Nội dung

onBeforeCopy NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 The onBeforeCopyevent handler not implemented in IE5/Mac fires before the actual copy action takes place whenever the user initia

Trang 1

reassigned unless the first parameter matches the case of the attribute currently associated with the object Instead, a new attribute with a different case sequence

is created

Attempting to manage the case-sensitivity of newly created attributes is fraught with peril, especially if you try to reuse names but with different case sequences I strongly recommend using default case-sensitivity controls for setAttribute()

and getAttribute() IE4+ imposes some limitations on the action resulting from the setAttribute()

method Any attribute you add via setAttribute()does not become part of the

attributescollection associated with the element While you can extract the value of such a newly added attribute via getAttribute(), you cannot access the new attribute from the attributescollection Thus, after creating a new attribute

as follows:

document.all.myTable.setAttribute(“currYear”, (new Date()).getFullYear())

you can access that attribute value through either of the following two statements:

var tableYear = document.all.myTable.getAttribute(“curryear”) var tableYear = document.all.myTable.currYear

However, you cannot access the attribute value with the following statement:

var tableYear = document.all.myTable.attributes[“currYear”]

See also the W3C DOM facilities for treating attributes as node objects in the dis-cussions of the getAttributeNode()and removeAttributeNode()methods ear-lier in this chapter

Example on the CD-ROM

Related Items:attributesproperty; document.createAttribute(),

getAttribute(), getAttributeNode(), removeAttribute(),

removeAttributeNode(), setAttributeNode()methods

setAttributeNode()

See removeAttributeNode()

setCapture(containerBoolean)

See releaseCapture()

setExpression(“propertyName”,

“expression”,”language”)

Returns: Nothing.

On the

CD-ROM

elementObject.setExpression()

Trang 2

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

Use the setExpression()method (not implemented in IE5/Mac) to assign the

result of an executable expression to the value of an element object property This

method can assign values to both HTML element objects and style objects that

belong to them

The setExpression()method is a scripted way of assigning expressions to

attributes But you can also assign expressions directly to style sheet definitions in

the HTML tag of an element using the expression()syntax, as in the following

example:

<P STYLE=”width:expression(document.body.style.width * 0.75)”>

The setExpression()method requires three parameters The first parameter is

the name of the property (in string form) to which you assign the expression

Property names are case-sensitive The second parameter is a string form of the

expression to be evaluated to supply a value for the property Expressions can refer

to global variables or properties of other objects in the same document (provided

the property is anything other than an array) An expression may also contain math

operators

Pay close attention to the data type of the evaluated value of the expression The

value must be a valid data type for the property For example, the URL of the body

background image must be a string But for numeric values, you can generally use

number and string types interchangeably because the values are converted to the

proper type for the property Even for expressions that evaluate to numbers,

encase the expression inside quotes It may not be necessary in all cases, but if you

get into the habit of using quotes, you’ll have fewer problems for strings or complex

expressions that require them

You are not limited to using JavaScript as the language for the expression

because you also specify the scripting language of the expression in the third

parameter Acceptable parameter values for the language are

JScript

VBScript

JavaScript

For all intents and purposes, JScript and JavaScript are the same Both languages

are ECMA-262 compatible

One reason to use setExpression()for dynamic properties is to let the

prop-erty always respond to the current conditions on the page For example, if you set a

property that is dependent on the current width of the body, then you want a

recal-culation that is applied to the property if the user resizes the window The browser

automatically responds to many events and updates any dynamic properties In

essence, the browser recalculates the expressions and applies the new values to

the property Keyboard events, in particular, trigger this kind of automatic

recalcu-lation for you But if your scripts perform actions on their own (in other words, not

elementObject.setExpression()

Trang 3

triggered by events), then your scripts need to force the recalculation of the expres-sions The document.recalc()method takes care of this, but you must invoke it

to force the recalculation of dynamic properties in these cases

Example (with Figure 15-1 and Listing 15-32) on the CD-ROM

Related Items:document.recalc(), removeExpression(), setExpression()

methods

swapNode(otherNodeObject)

Returns:Nodeobject reference

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

The swapNode()method (not implemented in IE5/Mac) exchanges the positions

of two nodes within an element hierarchy Contents of both nodes are preserved in their entirety during the exchange The single parameter must be a valid node object (perhaps created with document.createElement()or copied from an exist-ing node) A return value is a reference to the object whose swapNode()method was invoked

Example on the CD-ROM

Related Items:removeChild(), removeNode(), replaceChild(), replaceNode()

methods

tags(“tagName”)

Returns: Array of element objects.

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

The tags()method does not belong to every element, but it is a method of every collection of objects (such as all, forms, and elements) The method is

On the

CD-ROM

On the

CD-ROM

elementObjectCollection.tags()

Trang 4

best thought of as a kind of filter for the elements that belong to the current

collec-tion For example, to get an array of all P elements inside a document, use this

expression:

document.all.tags(“P”)

You must pass a parameter string consisting of the tag name you wish to extract

from the collection The tag name is case-insensitive

The return value is an array of references to the objects within the current

collection whose tags match the parameter If there are no matches, the returned

array has a length of zero If you need cross-browser compatibility, use the

getElementsByTagName()method described earlier in this chapter

Example on the CD-ROM

Related Item:getElementsByTagName()method

urns(“behaviorURN”)

Returns: Array of element objects.

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

The urns()method does not belong to every element, but it is a method of

every collection of objects You must pass a parameter string consisting of the URN

(Uniform Resource Name) of a behavior resource (most typically htcfor IE5)

assigned to one or more elements of the collection The parameter does not include

the extension of the filename If there is no matching behavior URN for the specified

parameter, the urns()method returns an array of zero length This method is

related to the behaviorUrnsproperty, which contains an array of behavior URNs

assigned to a single element object

Neither the behaviorUrns property nor the urns() method appear to be

work-ing as described by Microsoft Perhaps the potential exposure of URNs by script

was deemed a privacy risk As proven thus far with IE5 for Win32, the urns()

method always returns an array of zero length

Example on the CD-ROM

Related Item:behaviorUrnsproperty

On the

CD-ROM

Note

On the

CD-ROM

elementObjectCollection.urns()

Trang 5

Event handlers onActivate

onBeforeDeactivate

onDeactivate

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

The onActivateand onDeactivateevent handlers are new with IE5.5 But in some circumstances, they are very similar to the onFocusand onBlurevent han-dlers, respectively If an element receives focus, the onActivateevent fires for that element just before the onFocusevent fires; conversely, just prior to the element losing focus, events fire in the sequence: onBeforeDeactivate, onDeactivate,

onBlur Only elements that, by their nature, can accept focus (for example, links and form input controls) or that have a TABINDEXattribute set can become the active element (and therefore fire these events)

IE5.5 maintains the original onFocusand onBlurevent handlers But because the behaviors are so close to those of the onActivateand onDeactivateevents, I don’t recommend mixing the old and new event handler names in your coding style If you script exclusively for IE5.5+, then you can use the new terminology throughout

Example on the CD-ROM

Related Items:onBlur, onFocusevent handlers

onBeforeCopy

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

The onBeforeCopyevent handler (not implemented in IE5/Mac) fires before the actual copy action takes place whenever the user initiates a content copy action via the Edit menu (including the Ctrl+C keyboard shortcut) or the right-click context menu If the user accesses the Copy command via the Edit or context menu, the

onBeforeCopyevent fires before either menu displays In practice, the event may fire twice even though you expect it only once Just because the onBeforeCopy

event fires, it does not guarantee that a user will complete the copy operation (for example, the context menu may close before the user makes a selection)

Unlike paste-related events, the onBeforeCopyevent handler does not work with form input elements Just about any other HTML element is fair game, however

On the

CD-ROM

elementObject.onBeforeCopy

Trang 6

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

Related Items:onBeforeCut, onCopyevent handlers

onBeforeCut

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

The onBeforeCutevent handler fires before the actual cut action takes place

whenever the user initiates a content cut via the Edit menu (including the Ctrl+X

keyboard shortcut) or the right-click context menu If the user accesses the Cut

command via the Edit or context menu, the onBeforeCutevent fires before either

menu displays In practice, the event may fire twice even though you expect it only

once Just because the onBeforeCutevent fires, it does not guarantee that a user

will complete the cut operation (for example, the context menu may close before

the user makes a selection) If you add the onBeforeCutevent handler to an HTML

element, the context menu usually disables the Cut menu item But assigning a

JavaScript call to this event handler brings the Cut menu item to life

Example on the CD-ROM

Related Items:onBeforeCopy, onCutevent handlers

onBeforeDeactivate

See:onActivateevent handler

onBeforeEditFocus

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

The onBeforeEditFocusevent handler (not implemented in IE5/Mac) is

trig-gered whenever you edit an element on a page in an environment such as

Microsoft’s DHTML Editing ActiveX control or with the editable page content

fea-ture of IE5.5 This discussion focuses on the latter scenario because it is entirely

within the scope of client-side JavaScript The onBeforeEditFocusevent fires just

before the element receives its focus (There may be no onscreen feedback that

editing is turned on unless you script it yourself.) The event fires each time a user

clicks the element, even if the element just received edit focus elsewhere in the

same element

On the

CD-ROM

On the

CD-ROM

elementObject.onBeforeEditFocus

Trang 7

Example on the CD-ROM

Related Items:document.designMode, contentEditable, isContentEditable

properties

onBeforePaste

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

Like onBeforeCopyand onBeforeCut, the onBeforePasteevent (not imple-mented in IE5/Mac) occurs just prior to the display of either the context or menu bar Edit menu when the current object is selected (or has a selection within it) The primary value of this event comes when you use scripts to control the copy and paste process of a complex object Such an object may have multiple kinds of data associated with it, but your script captures only one of the data types Or, you may want to put some related data about the copied item (for example, the idproperty

of the element) into the clipboard By using the onBeforePasteevent handler to set the event.returnValueproperty to false, you guarantee that the pasted item

is enabled in the context or Edit menu (provided the clipboard is holding some content) A handler invoked by onPasteshould then apply the specific data subset from the clipboard to the currently selected item

Example on the CD-ROM

Related Items:onCopy, onCut, onPasteevent handlers

onBlur

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

The onBlurevent fires when an element that has focus is about to lose focus because some other element is about to receive focus For example, a text input element fires the onBlurevent when a user tabs from that element to the next one inside a form The onBlurevent of the first element fires before the onFocusevent

of the next element

The availability of the onBlurevent has expanded with succeeding generations

of script-capable browsers In the earlier versions, blur and focus were largely con-fined to text-oriented input elements (including the SELECT element) These are safe to use with all scriptable browser versions The windowobject received the

On the

CD-ROM

On the

CD-ROM

elementObject.onBlur

Trang 8

onBlurevent handler starting with NN3 and IE4 IE4 also extended the event

han-dler to more form elements, predominantly on the Windows operating system

because that OS has a user interface clue (the dotted rectangle) when items such as

buttons and links receive focus (so that you may act upon them by pressing the

keyboard’s spacebar) For IE5, the onBlurevent handler is available to virtually

every HTML element For most of those elements, however, blur and focus are not

possible unless you assign a value to the TABINDEXattribute of the element’s tag

For example, if you assign TABINDEX=1inside a <P>tag, the user can bring focus to

that paragraph (highlighted with the dotted rectangle in Windows) by clicking the

paragraph or pressing the Tab key until that item receives focus in sequence

If you plan to use the onBlurevent handler on window or text-oriented input

elements, be aware that there might be some unexpected and undesirable

conse-quences of scripting for the event For example, in IE, a windowobject that has

focus loses focus (and triggers the onBlurevent) if the user brings focus to any

element on the page (or even clicks a blank area on the page) Similarly, the

interac-tion between onBlur, onFocus, and the alert()dialog box can be problematic

with text input elements This is why I generally recommend using the onChange

event handler to trigger form validation routines If you should employ both the

onBlurand onChangeevent handler for the same element, the onChangeevent

fires before onBlur For more details about using this event handler for data

valida-tion, see Chapter 43

IE5.5 adds the onDeactivateevent handler, which fires immediately before the

onBlurevent handler Both the onBlurand onDeactivateevents can be blocked

if the onBeforeDeactivateevent handler function sets event.returnValueto

false

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

Related Items:blur(), focus()methods; onDeactivate, onBeforeDeactivate,

onFocus, onActivateevent handlers

onClick

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

The onClickevent fires when a user presses down (with the primary mouse

button) and releases the button with the pointer atop the element (both the down

and up strokes must be within the rectangle of the same element) The event also

fires with non-mouse click equivalents in operating systems such as Windows 95

and later For example, you can use the keyboard to give focus to a clickable object

and then press the spacebar or Enter key to perform the same action as clicking the

element In IE, if the element object supports the click()method, the onClick

event fires with the invocation of that method (notice that this does not apply to

Navigator)

On the

CD-ROM

elementObject.onClick

Trang 9

The availability of the onClickevent has expanded with succeeding generations

of script-capable browsers In the earlier versions, the event was limited primarily

to button style input elements (including checkbox and radio input elements) and links (Aelements with HREFattributes assigned to them) You can safely use this event handler for elements that date back to the earliest scriptable browsers In Navigator 4, the AREA element gained the onClickevent (and window, document, and layerobjects could capture onClickevents, as described in Chapter 29) In IE4+, virtually every element that you can see on a page can have an onClickevent handler defined for it and thereby respond to user clicks

Beginning with version 4 browsers, scripters could access more mouse-related events It is important to know the sequence of these incremental events as a user clicks or double-clicks an element The other related events are onMouseDown,

onMouseUp, and onDoubleClick The onMouseDownevent fires when the user makes contact with the mouse switch on the downstroke of a click action Next comes the onMouseUpevent (when the contact breaks) Only then does the

onClickevent fire — provided that the onMouseDownand onMouseUpevents have fired in the same object See the discussions on the onMouseDownand onMouseUp

events later in this chapter for examples of their usage

Interaction with the onDblClickevent is simple: the onClickevent fires first (after the first click), followed by the onDblClickevent (after the second click) See the discussion of the onDblClickevent handler later in this chapter for more about the interaction of these two event handlers

When used with objects that have intrinsic actions when users click them (namely links and areas), the onClickevent handler can perform all of the action — including navigating to the destination normally assigned to the HREFattribute of the element For example, to be compatible with all scriptable browsers, you can make an image clickable if you surround its tag with an <A>link tag This lets the

onClickevent of that tag substitute for the missing onClickevent handler of ear-lier <IMG>tags If you assign an onClickevent handler without special protection, the event handler will execute and the intrinsic action of the element will be carried out Therefore, you need to block the intrinsic action To accomplish this, the event handler must evaluate to the statement return false You can do this in two ways The first is to append a return falsestatement to the script statement assigned to the event handler:

<A HREF=”#” onClick=”yourFunction(); return false”><IMG ></A>

As an alternative, you can let the function invoked by the event handler supply the falsepart of the return falsestatement, as shown in the following

sequence:

function yourFunction() {

[statements that do something here]

return false }

<A HREF=”#” onClick=”return yourFunction()”><IMG ></A>

Either methdology is acceptable A third option is to not use the onClickevent handler at all, but assign a javascript:pseudo-URL to the HREFattribute (see the link object in Chapter 21)

elementObject.onClick

Trang 10

The event model in IE5+ provides one more way to prevent the intrinsic action of

an object from firing when a user clicks it If the onClickevent handler function

sets the returnValueproperty of the event object to false, the intrinsic action is

cancelled Simply include the following statement in the function invoked by the

event handler:

event.returnValue = false

The event model of the W3C DOM has a different approach to cancelling the

default action In the event handler function for an event, invoke the eventObj

cancelDefault()method

A common mistake made by scripting beginners is to use a submit type input

button as a button intended to perform some script action rather than submitting a

form The typical scenario is an INPUT element of type submitassigned an

onClickevent handler to perform some local action The submit input button has

an intrinsic behavior, just like links and areas While you can block the intrinsic

behavior, as just described, you should use an INPUT element of type button

If you are experiencing difficulty with an implementation of the onClickevent

handler (such as trying to find out which mouse button was used for the click), it

may be that the operating system or default browser behavior is getting in the way

of your scripting But you can usually get what you need via the onMouseDown

event handler (The onMouseUpevent may not fire when you use the secondary

mouse button to click an object.) Use the onClickevent handler whenever

possible to capture user clicks because this event behaves most like users are

accustomed to in their daily computing work But fall back on onMouseDownin an

emergency

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

Related Items:click()method; onContextMenu, onDblClick, onMouseDown,

onMouseUpevent handlers

onContextMenu

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

The onContextMenuevent (not implemented in IE5/Mac) fires when the user

clicks an object with the secondary (usually the right-hand) mouse button The

only click-related events that fire with the secondary button are onMouseDownand

onContextMenu

To block the intrinsic application menu display of the onContextMenuevent, use

any of the three event cancellation methodologies available in IE5+ (as just

described in the onClickevent handler description: two variations of evaluating

the event handler to return false; assigning falseto the event.returnValue

On the

CD-ROM

elementObject.onContextMenu

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

TỪ KHÓA LIÊN QUAN