Summary of how to use TextRange objects in JavaScript

Source: Internet
Author: User
Tags bitwise relative

The TextRange object is an advanced feature of Dynamic HTML (DHTML) that can be used 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.

The following are common properties and methods for 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 of the bound TextRange object and the left side of the containing TextRange object
Offsetleft gets the left position of the calculation of the object relative to the layout or the parent coordinates specified by the Offsetparent property
Offsettop gets the calculated top position of the object relative to the layout or the parent coordinates specified by the Offsetparent property
HTMLText Gets the width of the rectangle that binds the TextRange object
Text to set or get the texts contained within a range
Method

MoveStart Change range Start position
MoveEnd the end position of the change 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 to the given number of cells
ExecCommand executes commands on the current document, the current selection, or a given range
Select to place the current selection as the current object
FindText searches the text for text and sets the start and end points of the range to enclose the search string.
Using the TextRange object typically includes three basic steps:

1. Create a text range

2. Set start and end points

3. Operate on scope

The

code is as follows:


<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", "the 21st" of the "" The "" ", said:" The heroic hero, ambitious, the belly has a good plan, there is the machine of the universe, and the world's volunteers. " "Size=" ><br>


move cursor to <input type= "text" name= "Txtnum" size= "5" > Position


<input type= "button" Name= "Btnmove" value= "mobile" onclick= "Movecursor ()" >


</BODY>

1.createTextRange ()

Create a TextRange object, the body, TEXT, TextArea, button and other elements support this method. The method returns a TextRange object.

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

The move () method performs two actions. First, the method overlaps the current document at the position of the previous ending point, which is used 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 that specifies a character (character), 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 a parameter, or you can specify an integer value to indicate the number of cells, a positive sign to move forward, and a negative number to move backwards.

Note that the scope is still overlapping after the move () method is executed.

3.select ()

The Select () method selects text within the current text range, and the display cursor must also be used to implement it, because the so-called "cursor" can be understood as the range of boundary overlap

The

code is as follows:


<BODY>


<textarea name= "Txtbox" rows= "7" cols= "" id= "Txtbox" >


Chrysanthemum Station (with a theme song of gold)


Singer: Jay Chou Album: Still Fantasy


your tears, the light is weak


Pale Moon curved hook live in the past


night too long condensed into frost


who was in the attic, icy despair


rain gently drips the scarlet window


my whole life I was blown on paper by the wind


dream in the distance into a wisp of Chardonnay


with the wind you look


Chrysanthemum sad to hurt your smile has yellowing


flowers fall in the heart of my heart quietly dripping


The north wind night Young your shadow cut constantly


left me alone on the lake to Frost


</textarea><br>


<input type= "text" value= "Enter the content 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 the selection text


var num = 0;


if (document.selection)


num = Document.selection.createRange (). Text.length;


//Every time the function is called, the end point is the end, and the start point is the new starting point after the selection text is skipped


Rng.movestart ("character", num);


Rng.moveend ("character", txtBox.value.length);


//Search to select text


if (Rng.findtext (str))


Rng.select ();


//Search to the final range or not found, prompt search complete, and restore RNG the original scope (otherwise unable to perform a new search)


if (RNG.TEXT!=STR)


{  


alert ("Search completed");


rng = Txtbox.createtextrange ();


}


}  


</script>


</BODY>

The above example illustrates the use of the MoveStart () and Moveene () methods to select a range, and several methods appear as follows:

4.moveStart ("unit" [, Count]) and 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, and the end point is the last character

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

The

code is as follows:


function SelectText ()


{


var rng = Txtbox.createtextrange ();


Rng.movestart ("character", 1);


Rng.moveend ("character",-1);


Rng.select ();


}

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

5.collapse ([Boolean])

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

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

One of the most useful methods for TextRange objects is the FindText () method, whose default behavior is to browse the text range from the start point to the end point, searching for a case-insensitive string match. If an instance is found in a range, the start and end points of the range are placed in the text, the method returns True, or false, the start and end points are not moved. Method searches only for display text, and no tags or properties 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 contained in the search scope, and a negative value forcing 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 if only the whole word is matched. A parameter is an integer value that calculates a single value with a bitwise combination of values that can hold one or more settings. The value of matching the whole word is 2; matching case is 4; If you want to match only one item, it's enough to provide only the desired value, but for both behaviors, use the bitwise Action XOR operator (^ operator) to make the value 6.

The most common applications of the FindText () method include the search and replace operations in the range. and formatting an instance of a string, because the search usually starts with the current starting point of the range, so again the query wants to move the start point to the end of the matching text in the range (example 3), so that the FindText () 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 of example 3 can also be modified to:

The

code is as follows:


<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 final range or not found, prompt search complete, and restore RNG the original scope (otherwise unable to perform a new search)


Else


{  


alert ("Search completed");


rng = Txtbox.createtextrange ();


}


}  


</script>

6.parentElement ()

Parentelement () method returns a reference containing a text range container

Get the DOM object for the text selected by the cursor

The

code is as follows:


<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 text that belongs only to the body


<div> This is the text contained in the DIV </div>


<p> This is the text contained inside P </p>


<div><strong> This is the text contained in Div->strong </strong></div>


<input type= "button" value= select text after clicking "onclick=" Getparelem () ">


</BODY>

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.