Style Sheet Objects (Chapter 3 0 )

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 508 - 534)

A s earlier generations of scriptable browsers fade from the installed base, the event models of newer browsers become that much more im portant to scripters. Although cross-browser developers must concern themselves w ith the incom patibilities of as many as three d istin ct event models (NN4, IE4+, and W3C DOM used in NN6), scripts increasingly rely on inform ation conveyed by the event object to know where the event came from.

The importance of event object properties is clear when you see how modern DOMs bind events to objects. Although the

“old-fashioned” event handler attribute inside an element tag s till works, the prescribed ways to bind events to elements sim­

p ly assign a function reference to an event type belonging to the event. The significance of this approach is that event han­

dlers no longer receive custom parameters, such as references to the element that used to be passed via the t h i s operator. It becomes the job of the function to inspect the event object property that contains a reference to the target of the event.

Fortunately for scripters, the event object model (regard­

less of w hich ones you need to support) endows each event object w ith a lis t of valuable properties th a t enhance what event handler functions can do. In addition to character key and mouse button data, you can uncover the coordinates of a mouse event, the condition of m odifier keys, and even a refer­

ence to the object from w hich the cursor has ju st rolled (or where it went after leaving the bounds of the current object).

The code examples in this chapter are grouped by the event object model family. This means that the examples are w ritten to w ork only w ithin the associated DOM. For cross-browser handling of event objects, see the rest of the discussion in Chapter 29 of the JavaScript Bible. But use the examples here to fully understand the meaning of each event object’s properties and (in NN6) methods. Where possible, the listings that demon­

strate parallel properties in m ultiple object models look and behave the same to the user; the differences are in the code. As an exercise for the inquisitive, you could w rite a single-page version that combines syntax from m ultiple event objects mod­

els. Listings 29-17 and 29-22 would be good places to start.

♦ ♦ ♦ ♦ In This Chapter

Uncovering the coordinates and target element of a mouse event

Intercepting keyboard events

O bserving event propagation in different event object models

♦ 4- ♦ ♦

4 1 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Examples Highlights

♦ No fewer than four pairs of coordinate value properties arrive w ith the IE4+

event object. Listing 29-14 helps you understand w hat each pair of values rep­

resent w ith respect to regular body elements as well as positioned elements.

Follow the suggested steps to experience the meaning of the properties in a va rie ty of contexts.

♦ Load Listing 29-16 to see keyboard character data for all three keyboard events. Again, follow the suggested steps to understand im portant differences among keyboard event types and also different kinds of keys (characters ver­

sus non-characters).

♦ Listing 29-17 demonstrates how to derive a reference to the element that receives the event in the IE4+ event model.

♦ NN6 keyboard events get a w orkout in Listing 29-18, p articula rly the way the character and key codes reveal im portant details for different keyboard event types.

♦ All four pairs of event coordinate properties for NN6 are reported when you run Listing 29-19 and click on different elements.

♦ The im portant concepts associated w ith the NN6 event object’s

c u r r e n t T a r g e t and eventPhase properties are demonstrated in Listing 29-20. Be prepared to spend tim e w ith the page and the source code to under­

stand how events propagate through the element hierarchy.

♦ Listing 29-23 uses the NN6 e v e n t . timeStamp p roperty to calculate the instantaneous typing speed w ith in a text field.

NN4 event Object

Properties

d a t a

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

Compatibility ✓

Example

The page in Listing 29-12 contains little more than a TEXTAREA in w hich the URLs of dragged items are listed. To run this scrip t w ith o u t signing the scripts, turn on codebase principals, as directed in Chapter 46 of the JavaScript Bible.

To experim ent w ith this listing, load the page and drag any desktop icons that represent files, applications, o r folders to the window. Select m ultiple items and drag them all at once. Because the onDragDrop event handler evaluates to r e t u r n f a l s e , the files are not loaded into the window. If you want merely to look at the (NN4) eventobject.data

Chapter 13 ♦ Event Objects (Chapter 29) 4 1 1

URL and allow only some to process, you w ould generate an i f . . . e l s e construc­

tio n to return t r u e o r f a l s e t o the event handler as needed. A valué of r e t u r n t r u e allows the normal processing of the DragDrop event to take place after your event handler function has completed its processing.

Listing 29-12: Obtaining URLs o f a DragDrop Event's data Property

<HTML>

<HEAD>

<TITLE>Drag and Drop</TITLE>

<SCRIPT LANGUAGE-"JavaSeriptl .2">

function handleDrag(evt) {

netscape .s ec urit y .Pri vi 1egeManager.enablePri vi 1ege("Uni versal Brow se rR ea d") var URLArray = evt.data

netscape.security.PrivilegeManager.disablePrivilege("Uni versal BrowserRead") if (URLArray) {

document.forms[0].output.value = URLArray.join("\n") } else I

document.forms[0].outpit.value = "Nothing found."

}

return false

}

</SCRIPT>

</HEAD>

<B0DY o n D r ag Dr op =”return handleDrag(event)">

<B>Drag a URL to this window (KN4 only).</B>

<HR>

<F0RM>

URLs:<BR>

<TEXTAREA NAME="output" C0LS=7C R 0 W S = 4 X / T E X T A R E A X B R >

< INPUT TYPE="reset">

</F0RM>

</B0DY>

</HTML>

1ayerX 1ayerY pageX pageY screenX screenY

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

Compatibility ✓

(NN4) eventObject.layerX

4 1 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Example

You can see the effects of the coordinate systems and associated properties w ith the page in Listing 29-13. Part of the page contains a three-field readout of the layer-, page-, and screen-level properties. Two clickable objects are provided so tha t you can see the differences between an object not in any layer and an object residing w ith in a layer. The object not confined by a layer has its layer and page coordinates the same in the event object properties.

A dditional readouts display the event object coordinates fo r resizing and moving a window. If you maximize the window under Windows, the Navigator brow ser’s top-left corner is actually out of sight, four pixels up and to the left. That’s w hy the screenX and screenY values are both -4.

Listing 29-13: NN4 Event Coordinate Properties

<HTML>

<HEAD>

<TITLE>X and Y Event Properties</TITLE>

<SCRIPT LANGUAGE“ "JavaScript'^

function checkCoords(evt) { var form = document.forms[C]

form. 1 ayerCoords.val ue = evt.layerX + + evt.layerY form.pageCoords.val ue = evt.pageX + + evt.pageY form.screenCoords.val ue = evt.screenX + + evt.screenY return false

)

function checkSize(evt) {

document.forms[0].resizeCocrds.value - evt.layerX + + evt.layerY }

function checkLoc(evt) (

document.forms[0] .moveCoorcis.value = evt.screenX + + evt.screenY }

</SC RIPT>

</HEAD>

<B0DY onResize="checkSize(event)" onMove=”checkLoc(event)”>

<H1>X and Y Event Properties (NN4X/H1>

<HR>

<P>Click on the button and in the layer/image to see the coordinate values for the event object.</P>

<F0RM NAME="output">

<TABLE>

< T R X T D C0LSPAN=2>Mouse Event Coordinates:</TDX/TR>

< T R X T D ALIGN="right">layerX, layerY:C / T D X T D X I N P U T TYPE="text"

NAME="1 ayerCoords” S I Z E = 1 0 X / T D X / T R >

C T R X T D ALIGN="right">pageX, pageY:< / T D X T D X I N P U T TYPE=”text” NAHE="pageCoords”

S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN="right">screenX, s c r e e n Y : < / T D X T D X IN P U T TYPE="text"

NAME="screenCoords" S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN=”right"XINPUT TYPE="button" VALUE="Click Here"

onMouseDown="checkCoords( event ) " X / T D X / T R >

C T R X T D C 0 L S P A N = 2 X H R X / T D X / T R >

(NN4) eventobject.ịayerX

Chapter 13 ♦ Event Objects (Chapter 29) 4 1 3

< T R X T D C0LSPAN=2>Wi ndow Resize Coordinates :</TDX/TR>

< T R X T D ALIGN="right">layerX, l a y e r Y : < / T D X T O X I NP U T TYPE="text"

NAME="resi zeCoords" S I Z E = 1 0 X / T D X / T R >

< T R X T D C 0 L S P A N = 2 X H R X / T D X / T R >

< T R X T D C0LSPAN=2>Window Move Coordinates:</TDX/TR>

< T R X T D ALIGN=”right">screenX, screenY:</TDXTDXINPL)T TYPE-’text"

NAME="moveCoords” S I Z E = 1 0 X / T D X / T R >

</TABLE>

</F0RM>

<LAYER NAME-"display" BGC0L0R="coral" T0P=140 LEFT=300 HEIGHT=250 WIDTH=330>

<A HREF="javascript:void(0)" orCl ick=''return checkCoords(event)">

< I MG SRC="nile.gif" WIDTH=320 FEIGHT=240" B0RDER=0X/A>

</LAYER>

</B0DY>

</HTML>

IE4+ event Object

Properties

cli entX cli entY offsetX offsetY screenX screenY x

y

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

Compatibility / / /

Example

Listing 29-14 provides readings of all event coordinate properties in an interac­

tive way. An o n M o u s e D o w n event handler triggers all event handling, and you can click the mouse anywhere on the page to see what happens. You see the tag of the element targeted by the mouse event to help you visualize how some of the coordi­

nate properties are determined. An image is encased inside a positioned DIV ele­

ment to help you see what happens to some of the properties when the event is targeted inside a positioned element.

(IE) event.dientX

4 1 4 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 29-14: IE4+ Event Coordinate Properties

<HTML>

<HEAD>

<TITLE>X and Y Event Properties (IE4+X/TITLE>

<SCRIPT LANGUAGE-"JavaScript'^

function checkCoords() {

var form - document.forms[C]

form.srcEl emTag.val ue = ”< ” + event.srcElement.tagName + ">"

form.cl ientCoords.val ue = event.clientX + + event.clientY

form.pageCoords.value = (event.clientX + document.body.scroll.eft) + + (event.clientY + document.body.scrolITop)

form.offsetCoords. val ue = event.offsetX + ",n + event.offsetY form.screenCoords.value = event.screenX + ",n + event.screenY form.xyCoords.value = event.x + + event.y

form.parElem.value = "<" + event.srcElement.offsetParent.tagName + ">"

return false )

function handleSizeO (

document.forms[0].resizeCocrds.val ue = event.cl ientX + + event.clientY )

</SC RIPT>

</HEAD>

<B0DY onMouseDown="checkCoords()" onResize="handleSize() ">

<H1>X and Y Event Properties (IE4+X/H1>

<HR>

<P>Click on the button and in the DIV/image to see the coordinate values for the event object.</P>

<F0RM NAME="output">

<TABLE>

< T R X T D C0LSPAN=2>IE Mouse Evert Coordinates:</TDX/TR>

< T R X T D ALIGN=”right">srcElemert:</TDXTDXINPUT TYPE="text" NAME="srcEl emTag"

S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN=”right">cl ientX, cl i e n t Y : < / T D X T D X I N P U T TYPE="text"

NAME="clientCoords" SIZE=10X/TD>

<TD ALIGN=''right">.. .With scrol ling:</TDXTDXINPU T TYPE="text"

NAME="pageCoords" S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN="right">offsetX, o f f s e t Y : < / T D X T D X IN P U T TYPE="text"

NAME="offsetCoords" S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN="right">screenX, s c r e e n Y : < / T D X T D X IN P U T TYPE="text"

NAME="screenCoords" S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN="right">x, y : < / T D X T D X I N P U T TYPE="text" NAME="xyCoords”

SIZE=10X/TD>

<TD ALIGN="right">.. .Relative t o : < / T D X T O X I N P U T TYPE=''text" NAME="parElem"

S I Z E = 1 0 X / T D X / T R >

< T R X T D ALIGN=”right"XINPUT TYPE=”button" VALUE="Click H e r e " X / T D X / T R >

< T R X T D COLS PAN=2><HR></TDX/TR.>

< T R X T D C0LSPAN=2>Window Resize Coordinates:</TDX/TR>

< T R X T D ALIGN="right">cl ientX, cl i e n t Y : < / T D X T D X I N PU T TYPE="text"

NAME="resizeCoords" S I Z E = 1 0 X / T D X / T R >

</TABLE>

(IE) eve n t.d ien tx

Chapter 13 ♦ Event Objects (Chapter 29) 4 1 5

</F0RM>

<DIV ID="display" STYLE="position:relative; left:100">

< I MG SRC="nile.gif" WIDTH=320 hEIGHT=240" B0RDER=0>

</DIV>

</B0DY>

</HTML>

Here are some tasks to tr y w ith the page that loads from Listing 29-14 to help you understand the relationships among the various pairs of coordinate properties:

1. Click the dot above the “ i ” on the “Click Here” button label. The target ele­

ment is the button (INPUT) element, whose offsetParentis a table cell element. The of f setY value is v e ry low because you are near the top of the element’s own coordinate space. The client coordinates (and x and y), how­

ever, are relative to the viewable area in the window. If yo u r browser w indow is maximized in Windows, the screenX and cl i entX values w ill be the same;

the difference between screenY and cl i entY is the height of all the w indow chrome above the content region. W ith the w indow not scrolled at all, the client coordinates are the same w ith and w ith o u t scrolling taken in to account.

2. Jot down the various coordinate values and then scroll the page down slightly (clicking the scrollbar fires an event) and click the dot on the button again.

The c l i entY value shrinks because the page has moved upward relative to the viewable area, making the measure between the top of the area smaller w ith respect to the button. The Windows version does the right thing w ith the offset properties, by continuing to return values relative to the element’s own coordinate space; the Mac, unfortunately, subtracts the scrolled amount from the offset properties.

3. Click the large image. The client properties perform as expected for both Windows and Mac, as do the screen properties. For Windows, the x and y

properties co rre ctly return the event coordinates relative to the IMG ele­

m ent’s off setPa rent, which is the DIV element tha t surrounds it. Note, how­

ever, tha t the browser “ sees” the DIV as starting 10 pixels to the left of the image. In IE5.5/Windows, you can click w ith in those ten transparent pixels to the left of the image to click the DIV element. This padding is inserted auto­

m atically and impacts the coordinates of the x and y properties. A more reli­

able measure of the event inside the image is the offset properties. The same is true in the Macintosh version, as long as the page isn’t scrolled, in w hich case the scroll, ju st as in Step 2, affects the values above.

4. Click the top HR element under the heading. It may take a couple of tries to actually h it the element (you’ve made it when the HR element shows up in the s rcEl ement box). This is to reinforce the way the client properties provide coordinates w ith in the element itself (again, accept on the Mac when the page is scrolled). Clicking at the very left end of the rule, you eventually find the 0,0 coordinate.

(IE) event.dientX

4 1 6 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Finally, if you are a Windows user, here are tw o examples to t r y to see some of the unexpected behavior of coordinate properties.

1. W ith the page not scrolled, click anywhere along the rig h t side of the page, away from any text so that the BODY element is s rc E l ement. Because the BODY element theoretically fills the entire content region of the browser w in­

dow, all coordinate pairs except fo r the screen coordinates should be the same. But offset properties are tw o pixels less than all the others. By and large, this difference w on’t m atter in yo ur scripts, but you should be aware of this potential discrepancy if precise positioning is im portant. For inexplicable reasons, the offset properties are measured in a space tha t is inset tw o pixels from the left and top of the window. This is not the case in the Macintosh ver­

sion, where all value pairs are the same from the BODY perspective.

2. Click the text of the H I or p elements (just above and below the long horizon­

tal rule at the top of the page). In theory, the offset properties should be rela­

tive to the rectangles occupied by these elements (they’re block elements, after all). But instead, they’re measured in the same space as the client prop­

erties (plus the tw o pixels). This unexpected behavior doesn’t have anything to do w ith the cursor being a text cursor, because if you clic k inside any of the text box elements, th e ir offset properties are p roperly relative to th e ir own rectangles. This problem does not afflict the Macintosh version.

You can see fu rth e r examples of im portant event coordinate properties in action in the discussion of dragging elements around the IE page in Chapter 31 of the JavaScript Bible.

fromElement toElement

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

Compatibility y y y

Example

Listing 29-15 provides an example of how the f romEl ement and t oEl ement properties can reveal the life of the cursor action before and after it rolls in to an element. When you ro ll the cursor to the center box (a table cell), its onMouseOver event handler displays the text from the table cell from w hich the cursor arrived. In Figure 13-1, fo r example, the user has ju st rolled the cursor into the center box from the West box. If the cursor comes in from one of the corners (not easy to do), a dif­

ferent message is displayed.

(IE) event.fromElement

Chapter 13 ♦ Event Objects (Chapter 29) 4 1 7

Listing 29-15: Using the toElement and fromElement Properties

<HTML>

<HEAD>

<TITLE>fromEl ement and toElemert Properties</TITLE>

<STYLE TYPE="text/CSS">

.direction {background-color:#COFFFF; width:100; height:50; text-align¡center) //main (background-color:#FF666É; text-al ign:center)

</STYLE>

<SCRIPT LANGUAGE-"JavaScript">

function showArrival() (

var direction = (event.fromElement.innerText) ? event.fromElement.innerText

"parts unknown”

status = "Arrived from: " + direction }

function showDeparture() {

var direction = (event.toElement.innerText) ? event.toElement.innerText :

"parts unknown"

status = "Departed to: " + direction }

</SCRIPT>

</HEAD>

<B0DY>

<Hl>fromElement and toElement Froperties</Hl>

<HR>

<P>Roll the mouse to the center box and look for arrival information in the status bar. Roll the moise away from the center box and look for departure information in the status bar.</P>

<TABLE CELLSPACING=0 CELLPADDING=5>

< T R X T D X / T D X T D CLASS="di recti on " > N o r t h < / T D X T D X / T D X / T R >

< T R X T D CLASS="direction">West</TD>

<TD ID="main" onMouseOver="showArri val ( )" onMouseOut="showDepartu-'e( )">Rol 1 </TD>

<TD CLASS="direction">East</TDX/TR>

< T R X T D X / T D X T D CLASS ="d irect ion">South</TDXTDX/TDX/TR>

</TABLE>

</B0DY>

</HTML>

(IE) event.fromElement

4 1 8 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

3 f iu rn E le rn e n t d r ill tu E le m e n t P iu p e itie s - M ic iu s u it In te rn e t fc x p lu ie i Eile E dit V ie w F avorites I o o ls Help

ô- J $ a ầỡ J

Udck T o w a rd Stop Refresh Home Search Favorites History ü

Mail

~ 3

froniEIement and toElenient Properties

Roll the m ouse to the center b ox and look for arrival information in the status bar. Roll the mouse aw ay from the center b o x and look for departure information in the status b ar

N orth

W est

^ RoU East

South

A rrive d from : W est ỊằẶ My C om puter

Figure 1 3 - 1 : onMouseOver event object knows whence the pointer came.

This is a good example to experiment w ith in the browser, because it also reveals a potential lim itation. The element registered as the toEl ement o r from El ement must fire a mouse event to register itself w ith the browser. If not, the next element in the sequence tha t registers itself is the one acknowledged b y these properties.

For example, if you ro ll the mouse in to the center box and then extremely quickly ro ll the cursor to the bottom of the page, you may bypass the South box entirely.

The text tha t appears in the statusbar is actually the inner text of the BODY ele­

ment, w hich is the element tha t caught the firs t mouse event to register itself as the toEl ement for the center table cell.

keyCode

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

Compatibility / / /

Example

Listing 29-16 provides an additional play area to view the keyCode p ro p e rty for all three keyboard events while you type in to a TEXTAREA. You can use this page later as an authoring to o l to grab the precise codes fo r keyboard keys you may not be fam iliar w ith.

(IE) event.keyCode

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 508 - 534)

Tải bản đầy đủ (PDF)

(631 trang)