Summary of the usage of textRange objects in JavaScript, textrange

Source: Internet
Author: User

Summary of the usage of textRange objects in JavaScript, textrange

A TextRange object is an advanced feature of Dynamic HTML (DHTML). It can be used to perform many text-related tasks, such as searching and selecting texts. The text range allows you to select characters, words, and sentences from the document. A TextRange object is an abstract object that establishes the start and end positions on the text stream to be displayed in an HTML document.

The following are common attributes and methods of TextRange:

Attribute
  • BoundingHeight: gets the height of the rectangle bound to the TextRange object.
  • BoundingLeft gets the distance between the left side of the rectangle bound to the TextRange object and the left side of the rectangle containing the TextRange object.
  • OffsetLeft: obtains the left position of an object relative to the layout or the parent coordinate specified by the offsetParent attribute.
  • OffsetTop: obtains the top position of an object relative to the layout or the parent coordinate specified by the offsetParent attribute.
  • HtmlText gets the width of the rectangle bound to the TextRange object
  • Set or retrieve text in the range of text
Method
  • MoveStart: Change the start position of the range
  • MoveEnd changes the end position of the range
  • Collapse moves the insert point to the beginning or end of the current range
  • Move collapse the given text range and move the empty range to the order number.
  • ExecCommand
  • Select sets the current selection area to the current object
  • FindText searches for text in the text and sets the start and end points of the range to enclose the search string.

  Using a TextRange Object usually involves three basic steps:

1. Create a text range

2. Set the start point and end point

3. Operate the range

<Script language = "javascript"> function moveCursor () {var temp = this.txt Num. value; if (isNaN (temp) {alert ("enter a number"); return;} var rng = this.txt Test. createTextRange (); rng. move ("character", temp); rng. select ();} </script> </HEAD> <BODY> <input type = "text" name = "txtTest" value = "Ming Luo Guanzhong" Romance of the Three Kingdoms "21st: "the hero of the husband is ambitious and has good intentions. He has the opportunity to pack and store the universe. "Size =" 100 "> <br> move the cursor to the <input type =" text "name =" txtNum "size =" 5 "> position <input type =" button "name =" btnMove "value =" mobile "onclick =" moveCursor () "> </BODY>

  1. createTextRange ()

Create a TextRange object. All elements such as BODY, TEXT, TextArea, And BUTTON support this method. This method returns a TextRange object.

  2. move ("Unit" [, count])

The move () method performs two operations. First, the method overlaps the current document at the previous end point and serves as an insertion point. Next, it moves the insertion point forward or backward to any character, word, or sentence unit.

The first parameter of the method is a string, which specifies the unit of character, word, sentence, and textedit. The textedit value moves the insertion point to the end of the entire text range (No parameter is required ). If it is specified as the first three units, the default value is 1 when the parameter is ignored. You can also specify an integer to indicate the number of units. A positive number indicates moving forward, and a negative number indicates moving backward.

Note that after the move () method is executed, the range remains overlapping.

  3. select ()

The select () method selects the text within the current text range. The displayed cursor must also be used, because the so-called "cursor" can be understood as the range of overlapping boundaries.

<BODY> <textarea name = "txtBox" rows = "7" cols = "50" id = "txtBox"> chrysanthemum platform (filled with the golden armor theme song) ARTIST: Jay Chou's album: still, Fan tesi, your tears are weak, and the pale moon turns hook the past night is too long, and it turns into a Frome. Who is in the attic, the cold, desperate rain gently drips The Red window, my life on the paper is blown out of the wind and dream in from the distance into a ray of Xia with the wind dispersed your appearance chrysanthemum pale hurt your smile has been yellow flowers lost my mind quiet and quiet in the North Wind chaos night before the center of your shadows cut keep me alone in the lake cream </textarea> <br> <input type = "text" value = "Enter the content to be queried" id = "txtFind"> <input type = "button" value =" find the next "onclick =" findText (txtFind. value) "> <script language =" javascr ARIMA "> var rng = txtBox. createTextRange (); function findText (str) {if (str = "") return; // defines a variable as the offset of the moveStart () function, that is, the start point skips the selected text var num = 0; if (document. selection) num = document. selection. createRange (). text. length; // each time a function is called, the end point is the end point, and the start point is to skip the new start point rng after the selected text. moveStart ("character", num); rng. moveEnd ("character", txtBox. value. length); // select the text if (rng. findText (str) rng. select (); // if the final search range is not found, the system prompts that the search is complete and Restore the original rng range (otherwise a new search cannot be executed) if (rng. text! = Str) {alert ("Search completed"); rng = txtBox. createTextRange () ;}</script> </BODY>

The preceding example demonstrates how to use the moveStart () and moveEne () Methods to select a range. The following describes several methods:

  4. moveStart ("Unit" [, count]) and moveEnd ("Unit" [, count])

The moveStart () and moveEnd () methods are similar to the move () methods. By default, the start point is the first character of the container, and the end point is the last character.

We can modify the selectText () function above to prove that:

function selectText() {   var rng = txtBox.createTextRange();   rng.moveStart("character",1);   rng.moveEnd("character",-1);   rng.select(); }

Move the start point one character forward and the end point one character backward. After running, you can see that the selected range is the entire text range except 1st characters and the last one.

  5. collapse ([Boolean])

You can use the collapse () method to fold the text range from the current size into a single insertion point between characters. The optional parameter of the collapse () method is a Boolean value, indicating whether the range is the starting point of the current range or the ending point. The default value is true, and the start point is coincident:

 6. findText ("searchString" [, searchScope, flags])

One of the most useful methods for TextRange objects is the findText () method. The default behavior is to browse the text range from the start point to the end point and search for a case-insensitive string match. If an instance is found in the range, the start and end points of the range are put in this text, and the method returns true; otherwise, false is returned, and the start and end points are not moved. The method only searches for displayed text, and no tag or attribute is searched.

The optional parameter searchScope is an integer that indicates the number of characters from the start point. The larger the value, the more text contained in the search range; A negative value will force the search operation to search backward from the current start point.

The optional parameter flag is used to set whether the search is case-sensitive or whether it only matches the entire word. The parameter is an integer. It is used to calculate a single value based on a combination of digits. These values can accommodate one or more settings. The value of matching the entire word is 2, and the value of matching case is 4. If you only want to match one item, only the expected value is provided, use a bit to operate the XOR operator (^ operator) to set the value to 6.

The most commonly used findText () method applies the search and replacement operations in the range, as well as formatting an instance of a string, because the search usually starts with the current start point of the range, therefore, you need to move the start point to the end of the matched text in the range (for example, Example 3) before moving the start point, so that findText () can continue to browse the remaining text range to find another match. You can use the collapse (false) method to force the start point to move the end point of the first matching range. So the findText () function in Example 3 can also be changed:

<Script language = "javascript"> var rng = txtBox. createTextRange (); function findText (str) {if (str = "") return; if (rng. findText (str) {rng. select (); rng. collapse (false);} // if the final search range is not found, the system prompts that the search is complete and the original rng range is restored (otherwise, a new search cannot be executed) else {alert ("Search completed"); rng = txtBox. createTextRange () ;}}</script>

  6. parentElement ()

The parentElement () method returns a reference to a container that contains a text range.

Obtain the DOM object of the selected text with the cursor

<Script> function getParElem () {var rng = document. selection. createRange (); var container = rng. parentElement (); // alert (container. getAttribute ("id") | container. getAttribute ("value") | container. getAttribute ("type"); alert (container. tagName );} </script> </HEAD> <BODY> This is the text that only belongs to the Body. <div> This is the text contained in the div. </div> <p> This is included in p. text </p> <div> <strong> This is the text contained in div> strong </strong> </div> <input type = "button" value = "select click "onClick =" getParElem () "> </BODY>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.