Summary of how TextRange objects are used in JavaScript

Source: Internet
Author: User

The TextRange object is an advanced feature of Dynamic HTML (DHTML) that allows you to implement many text-related tasks, such as searching and selecting text. The text range allows you to selectively select characters, words, and sentences from the document. The TextRange object is an abstract object that establishes the start and end positions on the text stream that the HTML document will display.

Here are the common properties and methods of TextRange:

Property
  • Boundingheight gets the height of the rectangle that binds the TextRange object
  • Boundingleft gets the distance between the left edge of the rectangle that binds the TextRange object and the left side of the containing TextRange object
  • Offsetleft gets the calculated left position of the object relative to the layout or the parent coordinate specified by the Offsetparent property
  • OffsetTop gets the computed top position of the object relative to the layout or the parent coordinate specified by the Offsetparent property
  • HTMLText Gets the width of the rectangle that binds the TextRange object
  • Text to set or get the range contained within
Method
  • MoveStart to change the start position of a range
  • MoveEnd changing the end position of a range
  • Collapse move the insertion point to the beginning or end of the current range
  • Move collapses the given text range and moves the empty range by the given number of cells
  • ExecCommand executes a command on the current document, the current selection, or a given range
  • Select to place the current selection as the current object
  • FindText searches text and sets the start and end points of the range to enclose the search string.

  Using a TextRange object typically includes three basic steps:

1. Create a text range

2. Set the start point and end point

3. Operate on a range

<script language= "javascript" >  function movecursor ()  {  var temp = this.txtNum.value;   if (IsNaN (temp))  {  alert ("Please enter a number");  return;  }  var rng = This.txtTest.createTextRange ();  Rng.move ("character", temp);  Rng.select ();  }   </script>  </HEAD>  <BODY>  <input type= "text" name= "Txttest" value= "Ming Rod" kingdoms The 21st return to exercise Yue: "The hero of the husband, ambition, the abdomen has good plans, has the space of the machine, the world's ambition to huff and puff." "Size=" ><br>  move cursor to <input type= "text" name= "Txtnum" size= "5" > Locations  <input type= " Button "Name=" Btnmove "value=" Move "onclick=" Movecursor () ">   </BODY>

  1.createTextRange ()

Create a TextRange object that supports this method for elements such as BODY, TEXT, TextArea, button, and so on. The method returns a TextRange object.

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

The move () method performs two operations. First, the method overlaps the current document at the position of the previous end point, which is used as an insertion point, and next, it moves the insertion point forward or backward by any character, word, or sentence unit.

The first argument of a method is a string that specifies the units that have character (characters), Word (word), sentence (paragraph), TextEdit. The TextEdit value moves the insertion point to the end of the entire text range (no parameters are required). If you specify the first three units, the default value is 1 when you omit the parameter, you can specify an integer value to indicate the number of cells, positive numbers represent moving forward, and negative numbers represent backward movements.

Note that the range is still overlapping after the move () method executes.

  3.select ()

The Select () method selects the text in the current text range, where the display cursor must also be implemented, because the so-called "cursor" can be understood as the range of coincident boundaries

<BODY> <textarea name= "Txtbox" rows= "7" cols= "" id= "Txtbox" > Chrysanthemum terrace (Golden theme song) Singer: Jay Chou Album: Still Fant West your tears are weak The pale moon with wounds, the night is too long condensed into Frost is who in the attic cold despair rain gently streaming red window my life on paper by the wind disorderly dream in the distance into a wisp of the wind you look like chrysanthemum bleak hurt your smile has been suffused with yellow   On the night Young of the North Wind and the shadow of your shadows cut and keep me lonely in the Lake Frost </textarea><br> <input type= "text" value= "Enter what to Query" id= "Txtfind" > <input type= "button" value= "Find Next" onclick= "FindText (txtfind.value)" > <script language= "javascript" > 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 over the selection text var num = 0;         if (document.selection) num = Document.selection.createRange (). Text.length;         Each time the function is called, the end point is the end, and the start point is the new start point Rng.movestart ("character", num) after the selection text is skipped;         Rng.moveend ("character", txtBox.value.length);     After searching to select text if (Rng.findtext (str)) Rng.select (); Search to the last scope or not found, the prompt search is complete, and re-restore the RNG original scope (otherwise unable to perform a new search) if (rng.text!=STR) {alert ("Search completed");     RNG = Txtbox.createtextrange (); }} </script> </BODY>

The above example demonstrates the use of the MoveStart () and Moveene () methods to select a range, and the following are some of the methods that appear:

  4.moveStart ("unit" [, Count]) with MoveEnd ("unit" [, Count])

The MoveStart () and MoveEnd () methods are similar to the move () method, by default the start point is the first character of the container, 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 (); }

Moves the start point forward one character, the end point moves backward one character, and after running you can see that the selected range is the entire text range except the 1th character and the last 1 characters.

  5.collapse ([Boolean])

You can use the collapse () method to overlap a text range from the current dimension into a single insertion point between characters. The optional argument to the collapse () method is a Boolean value that indicates whether the range is coincident at the start point of the current range or the end point. The default value is true, coincident at the start point:

 6.findText ("SearchString" [, Searchscope,flags])

One of the most useful methods of TextRange objects is the FindText () method, whose default behavior is to browse through the text range from the start point to the end point, searching for a case-insensitive string match. If an instance is found in the range, the start and end points of the range are placed in the text, and the method returns true, otherwise false and the start and end points are not moved. Method searches only for display text, and no tags or attributes are searched.

An optional parameter, SearchScope, is an integer value that indicates the number of characters from the start point, the larger the value, the more text that is contained in the search scope, and negative values that force the search operation to search backwards from the current start point.

The optional parameter flag is used to set whether the search is case sensitive or whether it matches only the entire word. A parameter is an integer value that calculates a single value using a bitwise combination of mathematical methods that can hold one or more settings. Match the value of the whole Word to 2; Match case value is 4; If you want to match only one item, it is enough to supply only the desired value, but for both behaviors, use the bitwise operation XOR operator (^ operator) to make the value 6.

The most commonly used application of the FindText () method is to find and replace operations in the range, and to format an instance of a string, because the search usually starts at the current start point of the range, so again the query wants to move the start point to the end of the matched text in the range (example 3) before moving the FindText () Continue to browse for 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 matched range. So the FindText () function of example 3 can also be modified to:

<script language= "JavaScript" > var rng = Txtbox.createtextrange ();   function FindText (str) {  if (str== "")  return;      if (Rng.findtext (str)) {   rng.select ();   Rng.collapse (FALSE);   }  Search to the last range or not found, the prompt search is complete, and re-restore the RNG original scope (otherwise unable to perform a new search)  else   {   alert ("Search completed");      rng = Txtbox.createtextrange ();     } } </script>

  6.parentElement ()

The Parentelement () method returns a reference that contains a text range container

Gets the DOM object with the cursor selected text

<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 only the BODY text  <div> This is the text contained in the DIV </div>  <p> This is the text contained within P </p>  <div><strong> This is the text contained in the Div->strong </strong></ div>  <input type= "button" value= "Select text and click" onclick= "Getparelem ()" >  </BODY>

Summary of how TextRange objects are used in JavaScript

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.