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

JavaScript Bible, Gold Edition part 170 doc

10 48 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 94,96 KB

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

Nội dung

The onMouseDownevent handler in the BODY element triggers all event processing.IE events bubble up the hierarchy and no events are cancelled in this page, so all mouseDownevents eventual

Trang 1

Use The Evaluator (Chapter 13) to clone, rename, and append an element found in The Evaluator’s source code Begin by cloning the paragraph element named myP

along with all of its content Enter the following statement into the topmost text field:

a = document.getElementById(“myP”).cloneNode(true) The variable anow holds the clone of the original node, so you can change its ID

attribute at this point by entering the following statement:

a.setAttribute(“ID”, “Dolly”)

If you want to see the properties of the cloned node, enter ainto the lower text field The precise listing of properties you see depends on whether you use NN or IE; in either case, you should be able to locate the idproperty, whose value is now Dolly

As a final step, append this newly named node to the end of the bodyelement by entering the following statement into the topmost text field:

document.body.appendChild(a) You can now scroll down to the bottom of the page and see a duplicate of the con-tent But because the two nodes have different IDattributes, they cannot confuse scripts that need to address one or the other

componentFromPoint(x,y)

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

Example

You can experiment with this method in the code supplied with Listing 15-24 As presented, the method is associated with a TEXTAREA object that is specifically sized to display both vertical and horizontal scrollbars As you click various areas

of the TEXTAREA and the rest of the page, the status bar displays information about the location of the event with the help of the componentFromPoint()method The script utilizes a combination of the event.srcElementproperty and the

componentFromPoint()method to help you distinguish how you can use each one for different types of event processing The srcElementproperty is used initially as

a filter to decide whether the status bar will reveal further processing about the TEXTAREA element’s event details

elementObject.componentFromPoint()

Trang 2

The onMouseDownevent handler in the BODY element triggers all event processing.

IE events bubble up the hierarchy (and no events are cancelled in this page), so all

mouseDownevents eventually reach the BODY element Then, the whereInWorld()

function can compare each mouseDownevent from any element against the

textarea’s geography

Listing 15-24: Using the componentFromPoint() Method

<HTML>

<HEAD>

<TITLE>componentFromPoint() Method</TITLE>

<SCRIPT LANGUAGE=”JavaScript”>

function whereInWorld(elem) {

var x = event.clientX

var y = event.clientY

var component = document.all.myTextarea.componentFromPoint(x,y)

if (window.event.srcElement == document.all.myTextarea) {

if (component == “”) {

status = “mouseDown event occurred inside the element”

} else {

status = “mouseDown occurred on the element\’s “ + component

}

} else {

status = “mouseDown occurred “ + component + “ of the element”

}

}

</SCRIPT>

</HEAD>

<BODY onMouseDown=”whereInWorld()”>

<H1>componentFromPoint() Method</H1>

<HR>

<P>Tracking the mouseDown event relative to the textarea object View results in

status bar.</P>

<FORM>

<TEXTAREA NAME=”myTextarea” WRAP=”off” COLS=12 ROWS=4>

This is Line 1

This is Line 2

This is Line 3

This is Line 4

This is Line 5

This is Line 6

</TEXTAREA>

</FORM>

</BODY>

</HTML>

elementObject.componentFromPoint()

Trang 3

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

Example

Using The Evaluator (Chapter 13), see how the contains()method responds to the object combinations in each of the following statements as you enter them into the upper text box:

document.body.contains(document.all.myP) document.all.myP.contains(document.all.item(“myEM”)) document.all.myEM.contains(document.all.myEM) document.all.myEM.contains(document.all.myP) Feel free to test other object combinations within this page

detachEvent()

See attachEvent()

dispatchEvent(eventObject)

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

Example

Listing 15-25 demonstrates the dispatchEvent()method as defined in the W3C DOM Level 2 The behavior is identical to that of Listing 15-26, which demonstrates the IE5.5 equivalent: fireEvent() This example does not perform all intended actions in the first release of NN6 because the browser does not fully implement the

document.createEvent()method The example is designed to operate more com-pletely in a future version that supports event generation

elementObject.dispatchEvent()

Trang 4

Listing 15-25: Using the dispatchEvent() Method

<HTML>

<HEAD>

<STYLE TYPE=”text/css”>

#mySPAN {font-style:italic}

</STYLE>

<SCRIPT LANGUAGE=”JavaScript”>

// assemble a couple event object properties

function getEventProps(evt) {

var msg = “”

var elem = evt.target

msg += “event.target.nodeName: “ + elem.nodeName + “\n”

msg += “event.target.parentNode: “ + elem.parentNode.id + “\n”

msg += “event button: “ + evt.button

return msg

}

// onClick event handlers for body, myP, and mySPAN

function bodyClick(evt) {

var msg = “Click event processed in BODY\n\n”

msg += getEventProps(evt)

alert(msg)

checkCancelBubble(evt)

}

function pClick(evt) {

var msg = “Click event processed in P\n\n”

msg += getEventProps(evt)

alert(msg)

checkCancelBubble(evt)

}

function spanClick(evt) {

var msg = “Click event processed in SPAN\n\n”

msg += getEventProps(evt)

alert(msg)

checkCancelBubble(evt)

}

// cancel event bubbling if check box is checked

function checkCancelBubble(evt) {

if (document.controls.bubbleOn.checked) {

evt.stopPropagation()

}

}

// assign onClick event handlers to three elements

function init() {

document.body.onclick = bodyClick

document.getElementById(“myP”).onclick = pClick

Continued

elementObject.dispatchEvent()

Trang 5

Listing 15-25 (continued)

document.getElementById(“mySPAN”).onclick = spanClick }

// invoke fireEvent() on object whose ID is passed as parameter function doDispatch(objID, evt) {

// don’t let button clicks bubble evt.stopPropagation()

var newEvt = document.createEvent(“MouseEvent”)

if (newEvt) { newEvt.button = 3 document.getElementById(objID).dispatchEvent(newEvt) } else {

alert(“This browser version does not support the feature.”) }

}

</SCRIPT>

</HEAD>

<BODY ID=”myBODY” onLoad=”init()”>

<H1>fireEvent() Method</H1>

<HR>

<P ID=”myP”>This is a paragraph <SPAN ID=”mySPAN”>(with a nested SPAN)</SPAN> that receives click events.</SPAN></P>

<HR>

<P><B>Control Panel</B></P>

<FORM NAME=”controls”>

<P><INPUT TYPE=”checkbox” NAME=”bubbleOn”

onClick=”event.stopPropagation()”>Cancel event bubbling.</P>

<P><INPUT TYPE=”button” VALUE=”Fire Click Event on BODY”

onClick=”doDispatch(‘myBODY’, event)”></P>

<P><INPUT TYPE=”button” VALUE=”Fire Click Event on myP”

onClick=”doDispatch(‘myP’, event)”></P>

<P><INPUT TYPE=”button” VALUE=”Fire Click Event on mySPAN”

onClick=”doDispatch(‘mySPAN’, event)”></P>

</FORM>

</BODY>

</HTML>

fireEvent(“eventType”[, eventObjectRef])

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

elementObject.fireEvent()

Trang 6

The small laboratory of Listing 15-26 enables you to explore the possibilities of the

IE5.5 fireEvent()method while reinforcing event bubbling concepts in IE Three

nested element objects are assigned separate onClickevent handlers (via the

init()function invoked after the page loads — although you can also set these

event handlers via onClickattributes in the tags) Each handler displays an alert

whose content reveals which object’s event handler was triggered and the tag name

and ID of the object that received the event The default behavior of the page is to

allow event bubbling, but a checkbox enables you to turn off bubbling

After you load the page, click the italic segment (a nested SPAN element) to receive a

series of three alert boxes The first advises you that the SPAN element’s onClick

event handler is processing the event and that the SPAN element (whose ID is

mySPAN) is, indeed, the source element of the event Because event bubbling is

enabled by default, the event bubbles upward to the SPAN element’s next outermost

container: the myPparagraph element (However, mySPANis still the source element.)

Finally, the event reaches the BODY element If you click in the H1 element at the top

of the page, the event is not processed until it reaches the BODY element — although

the H1 element is the source element because that’s what you clicked In all cases,

when you explicitly click something to generate the onclickevent, the event’s

buttonproperty shows zero to signify the primary mouse button in IE

Now onto the real purpose of this example: the fireEvent()method Three

but-tons enable you to direct a click event to each of the three elements that have event

handlers defined for them The events fired this way are artificial, generated via the

createEventObject()method For demonstration purposes, the buttonproperty

of these scripted events is set to 3 This property value is assigned to the event

object that eventually gets directed to an element With event bubbling left on, the

events sent via fireEvent()behave just like the physical clicks on the elements

Similarly, if you disable event bubbling, the first event handler to process the event

cancels bubbling, and no further processing of that event occurs Notice that event

bubbling is cancelled within the event handlers that process the event To prevent

the clicks of the checkbox and action buttons from triggering the BODY element’s

onClickevent handlers, event bubbling is turned off for the buttons right away

Listing 15-26: Using the fireEvent() Method

<HTML>

<HEAD>

<STYLE TYPE=”text/css”>

#mySPAN {font-style:italic}

</STYLE>

<SCRIPT LANGUAGE=”JavaScript”>

// assemble a couple event object properties

Continued

elementObject.fireEvent()

Trang 7

Listing 15-26 (continued)

function getEventProps() { var msg = “”

var elem = event.srcElement msg += “event.srcElement.tagName: “ + elem.tagName + “\n” msg += “event.srcElement.id: “ + elem.id + “\n”

msg += “event button: “ + event.button return msg

} // onClick event handlers for body, myP, and mySPAN function bodyClick() {

var msg = “Click event processed in BODY\n\n”

msg += getEventProps() alert(msg)

checkCancelBubble() }

function pClick() { var msg = “Click event processed in P\n\n”

msg += getEventProps() alert(msg)

checkCancelBubble() }

function spanClick() { var msg = “Click event processed in SPAN\n\n”

msg += getEventProps() alert(msg)

checkCancelBubble() }

// cancel event bubbling if check box is checked function checkCancelBubble() {

event.cancelBubble = document.controls.bubbleOn.checked }

// assign onClick event handlers to three elements function init() {

document.body.onclick = bodyClick document.all.myP.onclick = pClick document.all.mySPAN.onclick = spanClick }

// invoke fireEvent() on object whose ID is passed as parameter function doFire(objID) {

var newEvt = document.createEventObject() newEvt.button = 3

document.all(objID).fireEvent(“onclick”, newEvt) // don’t let button clicks bubble

event.cancelBubble = true }

elementObject.fireEvent()

Trang 8

</HEAD>

<BODY ID=”myBODY” onLoad=”init()”>

<H1>fireEvent() Method</H1>

<HR>

<P ID=”myP”>This is a paragraph <SPAN ID=”mySPAN”>(with a nested SPAN)</SPAN>

that receives click events.</SPAN></P>

<HR>

<P><B>Control Panel</B></P>

<FORM NAME=”controls”>

<P><INPUT TYPE=”checkbox” NAME=”bubbleOn”

onClick=”event.cancelBubble=true”>Cancel event bubbling.</P>

<P><INPUT TYPE=”button” VALUE=”Fire Click Event on BODY”

onClick=”doFire(‘myBODY’)”></P>

<P><INPUT TYPE=”button” VALUE=”Fire Click Event on myP”

onClick=”doFire(‘myP’)”></P>

<P><INPUT TYPE=”button” VALUE=”Fire Click Event on mySPAN”

onClick=”doFire(‘mySPAN’)”></P>

</FORM>

</BODY>

</HTML>

focus()

See blur()

getAdjacentText(“position”)

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

Example

Use The Evaluator (Chapter 13) to examine all four adjacent text possibilities for

the myPand nested myEMelements in that document Enter each of the following

statements into the upper text box, and view the results:

document.all.myP.getAdjacentText(“beforeBegin”)

document.all.myP.getAdjacentText(“afterBegin”)

document.all.myP.getAdjacentText(“beforeEnd”)

document.all.myP.getAdjacentText(“afterEnd”)

elementObject.getAdjacentText()

Trang 9

The first and last statements return empty strings because the myPelement has no text fragments surrounding it The afterBeginversion returns the text fragment of the myPelement up to, but not including, the EM element nested inside The

beforeEndstring picks up after the end of the nested EM element and returns all text to the end of myP

Now, see what happens with the nested myEMelement:

document.all.myEM.getAdjacentText(“beforeBegin”) document.all.myEM.getAdjacentText(“afterBegin”) document.all.myEM.getAdjacentText(“beforeEnd”) document.all.myEM.getAdjacentText(“afterEnd”) Because this element has no nested elements, the afterBeginand beforeEnd

strings are identical: the same value as the innerTextproperty of the element

getAttribute(“attributeName”[,

caseSensitivity] )

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

Example

Use The Evaluator (Chapter 13) to experiment with the getAttribute()method for the elements in the page For IE4, use the document.allnotation IE5 and NN6 understand the W3C standard getElementById()method of addressing an ele-ment You can enter the following sample statements into the top text box to view attribute values

IE4:

document.all.myTable.getAttribute(“width”) document.all.myTable.getAttribute(“border”) IE5/NN6:

document.getElementById(“myTable”).getAttribute(“width”) document.getElementById(“myTable”).getAttribute(“border”)

elementObject.getAttribute()

Trang 10

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

Example

Use The Evaluator (Chapter 13) to explore the getAttributeNode()method in NN6

The Results TEXTAREA element provides several attributes to check out Because the

method returns an object, enter the following statements into the bottom text field so

you can view the properties of the attribute node object returned by the method:

document.getElementById(“output”).getAttributeNode(“COLS”)

document.getElementById(“output”).getAttributeNode(“ROWS”)

document.getElementById(“output”).getAttributeNode(“wrap”)

document.getElementById(“output”).getAttributeNode(“style”)

All (except the last) statements display a list of properties for each attribute node

object The last statement, however, returns nothing because the STYLEattribute is

not specified for the element

getBoundingClientRect()

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

Example

Listing 15-27 employs both the getBoundingClientRect()and

getClientRects()methods in a demonstration of how they differ A set of

ele-ments are grouped within a SPAN element named main The group consists of two

paragraphs and an unordered list

Two controls enable you to set the position of an underlying highlight rectangle to

any line of your choice A checkbox enables you to set whether the highlight

rectan-gle should be only as wide as the line or the full width of the bounding rectanrectan-gle for

the entire SPAN element

All the code is located in the hilite()function The SELECT and checkbox

ele-ments invoke this function Early in the function, the getClientRects()method is

elementObject.getBoundingClientRect()

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

TỪ KHÓA LIÊN QUAN