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

JavaScript Bible, Gold Edition part 33 pps

10 263 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 123,56 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.5The getClientRectsmethod returns an array of all TextRectangleobjects that fall within the current object the moment the method is invoked.. NN

Trang 1

for inserting, removing, reading, or writing attribute name–value pairs within the node map To a script, the value of the attributesproperty can behave the same

in both IE5 and the W3C DOM provided that scripts don’t have to dig too deeply into the nature of each object model’s idea of what an attribute object is

In IE5, an attribute object is a relatively simple object consisting of nodeName, nodeValue, and specifiedproperties In the W3C DOM, an attribute object is something more substantial, primarily because it inherits all the properties of the Nodeobject Table 5-9 compares the properties of an attribute object in NN6 and IE5

Table 15-9 Attribute Object Properties in NN6 and IE5

attributes childNodes firstChild lastChild name nextSibling

nodeType

ownerDocument parentNode previousSibling

value

Admittedly, the three properties implemented in IE5 are the most important, but the shortcut approach negates the object-oriented system of the W3C DOM

All of this is a long way to explain the W3C DOM getAttributeNode()method, which returns a W3C DOM attribute object The sole parameter of the method is a case-insensitive string version of the attribute’s name You can then use any of the properties shown in Table 15-9 to get or set attribute values Of course, HTML attributes are generally exposed as properties of HTML elements, so it is usually easier to read or write the object’s properties directly

Example on the CD-ROM

On the

CD-ROM

elementObject.getAttributeNode()

Trang 2

Related Items:attributesproperty; getAttribute(),

removeAttributeNode(), setAttributeNode()methods

getBoundingClientRect()

Returns:TextRectangleobject

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

IE5+ assigns to every content-holding element a rectangle that describes the

space that the element occupies on the page This rectangle is called a bounding

rectangle, and it is expressed in the IE5/Windows object model as a TextRectangle

object (even when the content is an image or some other kind of object) A

TextRectangleobject has four properties (top, left, bottom, and right) that are

the pixel coordinates that define the rectangle The getBoundingClientRect()

method returns a TextRectangleobject that describes the bounding rectangle of

the current object You can access an individual measure of an object’s bounding

rectangle, as in the following example:

var parTop = document.all.myP.getBoundingClientRect().top

For elements that consist of text, such as paragraphs, the dimensions of individual

TextRectangles for each line of text in the element influence the dimensions of the

bounding rectangle For example, if a paragraph contains two lines, and the second

line extends only halfway across the width of the first line, the width of the second

line’s TextRectangleobject is only as wide as the actual text in the second line But

because the first line extends close to the right margin, the width of the

encompass-ing boundencompass-ing rectangle is governed by that wider, first line TextRectangle

Therefore, an element’s bounding rectangle is as wide as its widest line and as tall as

the sum of the height of all TextRectangleobjects in the paragraph

Another method, getClientRects(), enables you to obtain a collection of

line-by-line TextRectangleobjects for an element Neither method is implemented in

IE5/Mac

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

Related Items:getClientRects()method; TextRectangleobject (Chapter 19)

getClientRects()

Returns: Array of TextRectangleobjects

On the

CD-ROM

elementObject.getClientRects()

Trang 3

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

The getClientRects()method returns an array of all TextRectangleobjects that fall within the current object the moment the method is invoked Each TextRectangleobject has its own top, left, bottom, and rightcoordinate prop-erties You can then, for example, loop through all objects in this array to calculate the pixel width of each line If you want to find out the aggregate height and/or max-imum width of the entire collection, you can use the getBoundingClientRect() method as a shortcut This method is not implemented in IE5/Mac

Example on the CD-ROM

Related Items:getBoundingClientRect()method; TextRectangleobject (Chapter 19)

getElementsByTagName(“tagName”)

Returns: Array of element objects.

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

The getElementsByTagName()method returns an array of all elements of the current object whose tags match the tag name supplied as the sole parameter to the method The tag name parameter must be in the form of a string and is case-insensi-tive The group of elements returned in the array includes only those elements that are within the containment scope of the current object Therefore, if you have two table objects in a document and you invoke the getElementsByTagName(“td”) method on one of them, the list of returned table cell elements is confined to those cells within the current table object The current element is not included in the returned array

The W3C DOM (but not implemented in IE5.x/Windows) accepts a wildcard

char-acter (“*”) as a parameter to the getElementsByTagName()method The resulting array of elements is similar to what IE4+ returns via the document.allcollection See Chapter 14 for ideas on simulating document.allin NN6 using this technique Internet Explorer provides additional alternate syntax for this method: the tags()method of the allcollection This alternate syntax also works in IE4 (see the allproperty earlier in this chapter)

On the

CD-ROM

elementObject.getElementsByTagName()

Trang 4

Example on the CD-ROM

Related Items:getElementById(), tags()methods

getExpression(“attributeName”)

Returns: String.

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

The getExpression()method (not implemented in IE5/Mac) returns the text of

the expression that was assigned to an element’s attribute via the setExpression()

method The returned value is not the value of the expression, but rather the

expres-sion itself If you want to find out the current value of the expresexpres-sion (assuming that

the variables used are within the scope of your script), you can use the eval()

func-tion on the call to getExpression() This action converts the string to a JavaScript

expression and returns the evaluated result

One parameter, a string version of the attribute name, is required

Example on the CD-ROM

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

methods

hasChildNodes()

Returns: Boolean.

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

The hasChildNodes()method returns trueif the current object has child

nodes nested within; it returns falseotherwise A child node is not necessarily the

same as a child element, so the following two expressions return truewhen the

current object has at least one child node:

document.getElementById(“myObject”).hasChildNodes()

document.getElementById(“myObject”).childNodes.length > 0

On the

CD-ROM

On the

CD-ROM

elementObject.hasChildNodes()

Trang 5

You cannot use the second expression interchangeably with the following state-ment (which uses the IE-only childrenproperty):

document.getElementById(“myObject”).children.length > 0 You generally use the hasChildNodes()method in a conditional expression to make sure such nodes exist before performing operations on them:

if (document.getElementById(“myObject”).hasChildNodes() {

statements that apply to child nodes

} Example on the CD-ROM

Related Items:childNodesproperty; appendChild(), removeChild(), replaceChild()methods

insertAdjacentElement(“location”,

elementObject)

Returns: Object.

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

The insertAdjacentElement()method (not implemented in IE5/Mac) inserts

an element object (coming from a variety of sources) in a specific position relative

to the current object Both parameters are required The first must be one of four possible case-insensitive locations for the insertion, shown in the following table:

Location Description

beforeBegin Before the current element’s start tag afterBegin After the start tag, but before any nested content beforeEnd Before the end tag, but after all other nested content afterEnd After the end tag

These locations are relative to the current object The element type of the cur-rent object (a block-level or inline element) has great bearing on how the inserted element is rendered For example, suppose you create a B element (using docu-ment.createElement()) and assign some inner text to it You then use

insertAdjacentElement()in an effort to insert this B element before some text

in a P element Because a P element is a block-level element, the location

On the

CD-ROM

elementObject.insertAdjacentElement()

Trang 6

beforeBeginplaces the new B element before the start tag of the P element This

means, however, that the bold text appears in a text line above the start of the P

element because a <P>tag begins a new block at the left margin of its container

(unless instructed otherwise by style sheets) The resulting HTML looks like the

following:

<B>The new element.</B><P>The original paragraph element.</P>

To make the new B element a part of the P element — but in front of the existing

P element’s content — use the afterBeginlocation The resulting HTML looks like

the following:

<P><B>The new element.</B>The original paragraph element.</P>

To complete the demonstration of the four location types, the following is the

result of the beforeEndlocation:

<P>The original paragraph element <B>The new element.</B></P>

and this is the result of the afterEndlocation:

<P>The original paragraph element.</P><B>The new element.</B>

The object to be inserted is a reference to an element object The object

refer-ence can come from any expression that evaluates to an element object or, more

likely, from the result of the document.createElement()method Bear in mind

that the object generated by document.createElement()initially has no content,

and all attribute values are set to default values Moreover, the object is passed to

insertAdjacentElement()by reference, which means that there is only one

instance of that object If you attempt to insert that object in two places with two

statements, the object is moved from the first location to the second If you need to

copy an existing object so that the original is not moved or otherwise disturbed by

this method, use the cloneNode()method to specify the trueparameter to

cap-ture all nested content of the node

Do not use this method to insert new table elements into a table Instead, use the

many table-specific insertion methods that better treat rows, columns, and cells of

a table (see Chapter 27) And if you wish to insert an element that surrounds the

current element or wraps all of the content of the current element, use the

applyElement()method

Example on the CD-ROM

Related Items:document.createElement(), applyElement()methods

insertAdjacentHTML(“location”, “HTMLtext”)

insertAdjacentText(“location”, “text”)

Returns: Nothing.

On the

CD-ROM

elementObject.insertAdjacentHTML()

Trang 7

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

These two methods insert HTML or straight text at a location relative to the current element They are intended for use after a page loads, rather than inserting content while the page loads (in which case you can use document.write() wher-ever you need evaluated content to appear on the page)

The first parameter must be one of four possible case-insensitive locations for the insertion, shown in the following table:

Location Description

beforeBegin Before the current element’s start tag afterBegin After the start tag, but before any nested content beforeEnd Before the end tag, but after all other nested content afterEnd After the end tag

These locations yield the same results as described in the insertAdjacentElement()function discussed earlier

Whether you use insertAdjacentHTML()or insertAdjacentText()depends

on the nature of your content and what you want the browser to do with it If the content contains HTML tags that you want the browser to interpret and render as if

it were part of the page source code, then use the insertAdjacentHTML()method All tags become objects in the document’s object model But if you want only to display some text (including HTML tags in their “raw” form), use

insertAdjacentText() The rendering engine does not interpret any tags included in the string passed as the second parameter Instead, these tags are dis-played as characters on the page This distinction is identical to the one between the innerHTMLand innerTextproperties

The difference between insertAdjacentHTML()and insertAdjacentElement()is the nature of the content that you insert The for-mer enables you to accumulate the HTML as a string, while the latter requires the creation of an element object Also, the two methods in this section work with IE4+ (including Mac versions), whereas insertAdjacentElement()requires the newer object model of IE5 and later

If the HTML you pass as the second parameter of insertAdjacentHTML() contains <SCRIPT>tags, you must set the DEFERattribute in the opening tag This prevents script statements from executing as you insert them

For inserting new elements into an existing table, use the variety of table object methods for managing rows, columns, and cells (see Chapter 27)

elementObject.insertAdjacentHTML()

Trang 8

Example on the CD-ROM

Related Items:innerText, innerHTML, outerText, outerHTMLproperties;

insertAdjacentElement(), replaceAdjacentText()methods

insertBefore(newChildNodeObject[,

referenceChildNode])

Returns:Nodeobject

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

The insertBefore()method is the W3C DOM syntax for inserting a new child

node into an existing element Node references for both parameters must be valid

Nodeobjects (including those that document.createElement()generates)

The behavior of this method might seem counter-intuitive at times If you include

the second parameter (a reference to an existing child node of the current

ele-ment), the new child node is inserted before that existing one But if you omit the

second parameter (or its value is null), the new child node is inserted as the last

child of the current element — in which case, the method acts the same as the

appendChild()method The true power of this method is summoned when you

specify that second parameter; from the point of view of a parent element, you can

drop a new child into any spot among its existing children

Bear in mind that the insertBefore()method works from a parent element

Internet Explorer provides additional methods, such as

insertAdjacentElement(), to operate from the perspective of what will become a

child element

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

Related Items:appendChild(), replaceChild(), removeChild(),

insertAdjacentElement()methods

item(index | “index” [, subIndex])

Returns: Object.

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

On the

CD-ROM

On the

CD-ROM

elementObjectCollection.item()

Trang 9

The item()method works with most objects that are themselves collections of other objects In the W3C DOM framework, these kinds of objects are known as

named node lists (for objects such as nodes and attributes) or HTML collections

(for objects such as elements of a form) While the W3C DOM defines the item() method, it does so with a single numeric parameter that is the index value of the desired object within the collection NN6 implements this version If you know the index number of the item, you can use JavaScript array syntax instead The follow-ing two statements return the same object reference:

document.getElementById(“myTable”).childNodes.item(2) document.getElementById(“myTable”).childNodes[2]

And for IE’s allobject, the index value for a given element is the same as the element’s sourceIndexproperty

IE4+ extends the possibilities by also allowing a string of the ID of an object within the collection (Integer values are required for the attributes, rules, and

TextRectangleobjects, however.) Additionally, if the collection has more than one object with the same ID (never a good idea except when necessary), a second numeric parameter enables you to select which identically named group you want (using zero-based index values within that subgroup) This obviously does not apply

to collections, such as attributes and rules, which have no ID associated with them The method returns a reference to the object specified by the parameters Example on the CD-ROM

Related Items: All object element properties that return collections (arrays) of

other objects

mergeAttributes(“sourceObject”)

Returns: Nothing.

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

The mergeAttributes()method (not implemented in IE5/Mac) is a convenient way to propagate attributes in newly created elements without painstakingly adding attributes one at a time Once you have an object whose attributes can function as a prototype for other elements, those attributes (except for the IDattribute) can be applied to a newly created element instantaneously

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

On the

CD-ROM

On the

CD-ROM

elementObject.mergeAttributes()

Trang 10

Related Items:clearAttributes(), cloneNode(), removeAttributes()

methods

normalize()

Returns: Nothing.

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

In the course of appending, inserting, removing, and replacing child nodes of an

element, it is conceivable that two text nodes can end up adjacent to each other

While this typically has no effect on the rendering of the content, some XML-centric

applications that rely heavily on the document node hierarchy to interpret content

properly may not like having two text nodes sitting next to each other The “proper”

form of a node hierarchy is for a single text node to be bounded by other node

types The normalize()method sweeps through the child nodes of the current

node object and combines adjacent text nodes into a single text node The effect

obviously impacts the number of child nodes of an element, but it also cleanses the

nested node hierarchy

Example on the CD-ROM

Related Items:document.createTextNode(), appendChild(), insertBefore(),

removeChild(), replaceChild()methods

releaseCapture()

setCapture(containerBoolean)

Returns: Nothing.

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

You can instruct a single object on an IE5+/Windows page to capture all mouse

events (onmousedown, onmouseup, onmousemove, onmouseout, onmouseover,

onclick, and ondblclick) via the IE-specific setCapture()method This type of

event capture is somewhat similar to event capture mechanisms of NN4 and NN6

(which are quite different in and of themselves) However, the syntax is entirely

different, as is the overall approach to the code that handles events (see Chapter 29

on the Eventobject)

On the

CD-ROM

elementObject.releaseCapture()

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

TỪ KHÓA LIÊN QUAN