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

JavaScript Bible, Gold Edition part 193 potx

10 109 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

CD-412 Part VI ✦ Appendixes assigned to its nested text node after the page loads (in the init() function). That fixed range becomes a solid reference point for you to use while you select text in the paragraph. Unfortunately, the window object method that converts a user selection into an object is not connected correctly in the first release of NN6. Even if it were, the inverted values returned by the compareBoundaryPoints() method would give you incorrect results. Try this example on subsequent versions of NN6. After you make a selection, all four versions of the compareBoundaryPoints() method run to compare the start and end points of the fixed range against your selection. One column of the results table shows the raw value returned by the compareBoundaryPoints() method, while the third column puts the results into plain language. To see how this page works, begin by selecting the first word of the fixed text range (carefully drag the selection from the first red character). You can see that the starting positions of both ranges are the same, because the returned value is 0. Because all of the invocations of the compareBoundaryPoints() method are on the fixed text range, all comparisons are from the point of view of that range. Thus, the first row of the table for the START_TO_END parameter indicates that the start point of the fixed range comes before the end point of the selection, yielding a return value of -1. Other selections to make include: ✦ Text that starts before the fixed range and ends inside the range ✦ Text that starts inside the fixed range and ends beyond the range ✦ Text that starts and ends precisely at the fixed range boundaries ✦ Text that starts and ends before the fixed range ✦ Text that starts after the fixed range Study the returned values and the plain language results and see how they align with the selection you made. Listing 19-4: Lab for NN6 compareBoundaryPoints() Method <HTML> <HEAD> <TITLE>TextRange.compareBoundaryPoints() Method</TITLE> <STYLE TYPE=”text/css”> TD {text-align:center} .propName {font-family:Courier, monospace} Note Range.compareBoundaryPoints() CD-413 Appendix F ✦ Examples from Parts III and IV #fixedRangeElem {color:red; font-weight:bold} </STYLE> <SCRIPT LANGUAGE=”JavaScript”> var fixedRange function setAndShowRangeData() { try { var selectedRange = window.getSelection() selectedRange = selectedRange.getRangeAt(0) var result1 = fixedRange.compareBoundaryPoints(Range.START_TO_END, selectedRange) var result2 = fixedRange.compareBoundaryPoints(Range.START_TO_START, selectedRange) var result3 = fixedRange.compareBoundaryPoints(Range.END_TO_START, selectedRange) var result4 = fixedRange.compareBoundaryPoints(Range.END_TO_END, selectedRange) document.getElementById(“B1”).innerHTML = result1 document.getElementById(“compare1”).innerHTML = getDescription(result1) document.getElementById(“B2”).innerHTML = result2 document.getElementById(“compare2”).innerHTML = getDescription(result2) document.getElementById(“B3”).innerHTML = result3 document.getElementById(“compare3”).innerHTML = getDescription(result3) document.getElementById(“B4”).innerHTML = result4 document.getElementById(“compare4”).innerHTML = getDescription(result4) } catch(err) { alert(“Vital Range object services are not yet implemented in this browser.”) } } function getDescription(comparisonValue) { switch (comparisonValue) { case -1 : return “comes before” break case 0 : return “is the same as” break case 1 : return “comes after” break default : return “vs.” } } Continued Range.compareBoundaryPoints() CD-414 Part VI ✦ Appendixes Listing 19-4 (continued) function init() { fixedRange = document.createRange() fixedRange.selectNodeContents(document.getElementById(“fixedRangeElem”). firstChild) fixedRange.setEnd(fixedRange.endContainer, fixedRange.endContainer.nodeValue.length) } </SCRIPT> </HEAD> <BODY onLoad=”init()”> <H1>TextRange.compareBoundaryPoints() Method</H1> <HR> <P>Select text in the paragraph in various places relative to the fixed text range (shown in red). See the relations between the fixed and selected ranges with respect to their start and end points.</P> <TABLE ID=”results” BORDER=1 CELLSPACING=2 CELLPADDING=2> <TR><TH>Property</TH><TH>Returned Value</TH><TH>Fixed Range vs. Selection</TR> <TR> <TD CLASS=”propName”>StartToEnd</TD> <TD CLASS=”count” ID=”B1”>&nbsp;</TD> <TD CLASS=”count” ID=”C1”>Start of Fixed <SPAN ID=”compare1”>vs.</SPAN> End of Selection</TD> </TR> <TR> <TD CLASS=”propName”>StartToStart</TD> <TD CLASS=”count” ID=”B2”>&nbsp;</TD> <TD CLASS=”count” ID=”C2”>Start of Fixed <SPAN ID=”compare2”>vs.</SPAN> Start of Selection</TD> </TR> <TR> <TD CLASS=”propName”>EndToStart</TD> <TD CLASS=”count” ID=”B3”>&nbsp;</TD> <TD CLASS=”count” ID=”C3”>End of Fixed <SPAN ID=”compare3”>vs.</SPAN> Start of Selection</TD> </TR> <TR> <TD CLASS=”propName”>EndToEnd</TD> <TD CLASS=”count” ID=”B4”>&nbsp;</TD> <TD CLASS=”count” ID=”C4”>End of Fixed <SPAN ID=”compare4”>vs.</SPAN> End of Selection</TD> </TR> </TABLE> <HR> <P onMouseUp=”setAndShowRangeData()”> Range.compareBoundaryPoints() CD-415 Appendix F ✦ Examples from Parts III and IV Lorem ipsum dolor sit, <SPAN ID=”fixedRangeElem”>consectetaur adipisicing elit</SPAN>, sed do eiusmod tempor incididunt ut labore et dolore aliqua. Ut enim adminim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</P> </BODY> </HTML> createContextualFragment(“text”) NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Example Use The Evaluator (Chapter 13) to create a document fragment and replace an existing document tree node with the fragment. Begin by creating the range and fragment: a = document.createRange() a.selectNode(document.body) b = a.createContextualFragment(“<SPAN STYLE=’font-size:22pt’>a bunch of </SPAN>”) This fragment consists of a SPAN element node with a text node nested inside. At this point, you can inspect the properties of the document fragment by entering b into the bottom text box. To replace the myEM element on the page with this new fragment, use the replaceChild() method on the enclosing myP element: document.getElementById(“myP”).replaceChild(b, document.getElementById(“myEM”)) The fragment now becomes a legitimate child node of the myP element and can be referenced like any node in the document tree. For example, if you enter the follow- ing statement into the top text box of The Evaluator, you can retrieve a copy of the text node inside the new SPAN element: document.getElementById(“myP”).childNodes[1].firstChild.nodeValue Range.createContextualFragment() CD-416 Part VI ✦ Appendixes deleteContents() NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Example Use The Evaluator (Chapter 13) to experiment with deleting contents of both a text node and a complete element node. Begin by creating a text range for the text node inside the myEM element (enter the third statement, which wraps below, as one continous expression): a = document.createRange() a.setStart(document.getElementById(“myEM”).firstChild, 0) a.setEnd(document.getElementById(“myEM”).lastChild, document.getElementById(“myEM”).lastChild.length) Verify the makeup of the range by entering a into the bottom text box and inspect its properties. Both containers are text nodes (they happen to be the same text node), and offsets are measured by character positions. Now, delete the contents of the range: a.deleteContents() The italicized word “all” is gone from the tree, but the myEM element is still there. To prove it, put some new text inside the element: document.getElementById(“myEM”).innerHTML = “a band of “ The italic style of the EM element applies to the text, as it should. Next, adjust the range boundaries to include the myEM element tags, as well: a.selectNode(document.getElementById(“myEM”)) Inspect the Range object’s properties again by entering a into the bottom text box. The container nodes are the P element that surrounds the EM element; the offset values are measured in nodes. Delete the range’s contents: a.deleteContents() Range.deleteContents() CD-417 Appendix F ✦ Examples from Parts III and IV Not only is the italicized text gone, but the myEM element is gone, too. The myP ele- ment now has but one child node, the text node inside. The following entries into the top text box of The Evaluator verify this fact: document.getElementById(“myP”).childNodes.length document.getElementById(“myP”).childNodes[0].nodeValue If you try this example in early versions of NN6, however, you see that the deleteContents() method also removes the text node following the myEM ele- ment. This is buggy behavior, demonstrating that the method works best on text nodes, rather than elements. extractContents() NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Example When Netscape outfits the NN6 browser with the extractContents() method, use The Evaluator (Chapter 13) to see how the method works. Begin by creating a new range object that contains the text of the myP paragraph element. a = document.createRange() a.selectNode(document.getElementById(“myP”)) Next, extract the original range’s content and preserve the copy in variable b: b = a.extractContents() Move the original range so that it is an insertion point at the end of the body by first expanding it to encompass the entire body and then collapse it to the end a.selectNode(document.body) a.collapse(false) Now, insert the extracted fragment at the very end of the body: a.insertNode(b) If you scroll to the bottom of the page, you see a copy of the text. Range.extractContents() CD-418 Part VI ✦ Appendixes insertNode(nodeReference) NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Example Listing 19-5, which relies on selection and Range object features not implemented in the first release of NN6, demonstrates the insertNode() method plus some additional items from the NN6 selection object. The example even includes a rudimentary undo buffer for scripted changes to a text range. In the page generated by this listing, users can select any text in a paragraph and have the script automat- ically convert the text to all uppercase characters. The task of replacing a selection with other text requires several steps, starting with the selection, which is retrieved via the window.getSelection() method. After making sure the selection contains some text (that is, the selection isn’t collapsed), the selection is preserved as a range object so that the starting text can be stored in a global variable (as a prop- erty of the undoBuffer global variable object). After that, the selection is deleted from the document tree, leaving the selection as a collapsed insertion point. A copy of that selection in the form of a range object is preserved in the undoBuffer object so that the undo script knows where to reinsert the original text. A new text node is created with an uppercase version of the original text, and, finally, the insertNode() method is invoked to stick the converted text into the collapsed range. Undoing this operation works in reverse. Original locations and strings are copied from the undoBuffer object. After creating the range with the old start and end points (which represent a collapsed insertion point), the resurrected text (con- verted to a text node) is inserted into the collapsed range. For good housekeeping, the undoBuffer object is restored to its unused form. Listing 19-5: Inserting a Node into a Range <HTML> <HEAD> <TITLE>NN Selection Object Replacement</TITLE> <SCRIPT LANGUAGE=”JavaScript”> var undoBuffer = {rng:null, txt:””} function convertSelection() { var sel, grossRng, netRng, newText try { sel = window.getSelection() Range.insertNode() CD-419 Appendix F ✦ Examples from Parts III and IV if (!sel.isCollapsed) { grossRng = sel.getRangeAt(0) undoBuffer.txt = grossRng.toString() sel.deleteFromDocument() netRng = sel.getRangeAt(0) undoBuffer.rng = netRng newText = document.createTextNode(undoBuffer.txt.toUpperCase()) netRng.insertNode(newText) } } catch(err) { alert(“Vital Range object services are not yet implemented in this browser.”) } } function undoConversion() { var rng, oldText if (undoBuffer.rng) { rng = document.createRange() rng.setStart(undoBuffer.rng.startParent, undoBuffer.rng.startOffset) rng.setEnd(undoBuffer.rng.endParent, undoBuffer.rng.endOffset) oldText = document.createTextNode(undoBuffer.txt) rng.insertNode(oldText) undoBuffer.rng = null undoBuffer.txt = “” } } </SCRIPT> </HEAD> <BODY> <H1 ID=”H1_1”>NN6 Selection Object Replacement</H1> <HR> <P ID=”P_1” onMouseUp=”convertSelection()”>This paragraph contains text that you can select. Selections are deleted and replaced by all uppercase versions of the selected text.</P> <BUTTON onClick=”undoConversion()”>Undo Last</BUTTON> <BUTTON onClick=”location.reload(true)”>Start Over</BUTTON> </BODY> </HTML> isValidFragment(“HTMLText”) NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Range.isValidFragment() CD-420 Part VI ✦ Appendixes Example You can try the validity of any strings that you like in The Evaluator (Chapter 13). You will discover, however, that the object model can make a document fragment out of just about any string. For instance, if you attempt to create a document frag- ment out of some random text and an end tag, the document fragment will consist of a text node and an element node of the type indicated by the end tag. selectNode(nodeReference) selectNodeContents(nodeReference) NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Example Use The Evaluator (Chapter 13) to see the behavior of both the selectNode() and selectNodeContents() methods work. Begin by creating a new range object. a = document.createRange() Set the range boundaries to include the myP element node: a.selectNode(document.getElementById(“myP”)) Enter a into the bottom text box to view the properties of the range. Notice that because the range has selected the entire paragraph node, the container of the range’s start and end points is the BODY element of the page (the parent element of the myP element). Now change the range so that it encompasses only the contents of the myP element: a.selectNodeContents(document.getElementById(“myP”)) Click the List Properties button to view the current properties of the range. The container of the range’s boundary points is the P element that holds the element’s contents. Range.selectNode() CD-421 Appendix F ✦ Examples from Parts III and IV setEnd(nodeReference, offset) setStart(nodeReference, offset) NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ Example Use The Evaluator (Chapter 13) to experiment with both the setStart() and setEnd() methods. Begin by creating a new range object. a = document.createRange() For the first range, set the start and end points to encompass the second node (the myEM element) inside the myP element: a.setStart(document.getElementById(“myP”), 1) a.setEnd(document.getElementById(“myP”), 2) The text encompassed by the range consists of the word “all” plus the trailing space that is contained by the myEM element. Prove this by entering the following statement into the top text box: a.toString() If you then click the Results box to the right of the word “all,” you see that the results contain the trailing space. Yet, if you examine the properties of the range (enter a into the bottom text box), you see that the range is defined as actually starting before the myEM element and ending after it. Next, adjust the start point of the range to a character position inside the first text node of the myP element: a.setStart(document.getElementById(“myP”).firstChild, 11) Click the List Properties button to see that the startContainer property of the range is the text node, and that the startOffset measures the character position. All end boundary properties, however, have not changed. Enter a.toString() in the top box again to see that the range now encompasses text from two of the nodes inside the myP element. Range.setEnd() . monospace} Note Range.compareBoundaryPoints() CD-413 Appendix F ✦ Examples from Parts III and IV #fixedRangeElem {color:red; font-weight:bold} </STYLE> <SCRIPT LANGUAGE= JavaScript > var fixedRange function setAndShowRangeData(). CD-412 Part VI ✦ Appendixes assigned to its nested text node after the page loads (in the init() function) “comes after” break default : return “vs.” } } Continued Range.compareBoundaryPoints() CD-414 Part VI ✦ Appendixes Listing 19-4 (continued) function init() { fixedRange = document.createRange() fixedRange.selectNodeContents(document.getElementById(“fixedRangeElem”). firstChild) fixedRange.setEnd(fixedRange.endContainer, fixedRange.endContainer.nodeValue.length) } </SCRIPT> </HEAD> <BODY

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

Xem thêm: JavaScript Bible, Gold Edition part 193 potx

TỪ KHÓA LIÊN QUAN