Details about textrange objects-search and selection

Source: Internet
Author: User

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

--------------------------------------------------------------------------------

Example 1:

<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>

<Input type = "text" name = "txttest" value = "Ming · Luo Guanzhong" Romance of the Three Kingdoms "21st:" hero man, ambitious, considerate, there is a chance to pack the universe, and the ambition of the world is also. "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 ()">

The above example implements a simple cursor positioning, involving several textrange Methods

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 where the boundary is overlapped.

--------------------------------------------------------------------------------

Example 2:

<Script language = "JavaScript">

Function selecttext (SP, EP)
{
If (isnan (SP) | isnan (EP ))
{
Alert ("enter a number! ");
Return;
}
// Automatic conversion of weak languages
SP = sp * 1;
Ep = EP * 1;
If (SP> = EP)
{
Alert ("the start position must be smaller than the end position ");
Return;
}
If (SP> txtbox. value. Length | EP> txtbox. value. length)
{
Alert ("Maximum number of current characters" + txtbox. value. Length + ", please enter ");
Return;
}
VaR RNG = this.txt box. createTextRange ();

// Overlap the start and end points with the start position of the container
RNG. movestart ("character",-txtbox. value. Length );
RNG. moveend ("character",-txtbox. value. Length );
RNG. Collapse (true );

// Move by parameter value
RNG. movestart ("character", SP );
RNG. moveend ("character", EP );

RNG. Select ();
}

</SCRIPT>

<Textarea name = "txtbox" rows = "7" Cols = "50" id = "txtbox">
Thousands of miles away
Artist: Jay Chou/Fei yuqing album: Still fan tersi

The eaves are like a cliff, the wind is like a sea, and I will wait for Yan to return.
Scheduled for an accident. You walked away quietly.
The story cannot be seen clearly outside the city
I'm sorry you cannot hear the news.

Who opened the ending scene on the windowsill?
The Treasure of the future cannot be removed.
I'm leaving you thousands of miles away, you're black and white
Silence may not be too distant in love
Are you still there
Why are you waiting for life?

The cry of tears entered the forest to find a line of green moss
Days out of the mountains, the rain fell into the flower platform and I were white
The cry of tears entered the forest to find a line of green moss
I'm waiting for you to come.
</Textarea> <br>

Specify the selection range:

<Input type = "text" size = "5" id = "txtstart">

-- <Input type = "text" size = "5" id = "txtend">

<Input type = "button" value = "select" onclick = "selecttext (txtstart. Value, txtend. Value)">

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:

--------------------------------------------------------------------------------

Example 2:

<Textarea name = "txtbox" rows = "7" Cols = "50" id = "txtbox">
Chrysanthemum (full city with the theme song of golden armor)
Artist: Jay Chou album: Still fan tersi

Your tears hurt
The pale moon bends to hide the past
The night is too long to cool
Who's cold despair in the attic?
The light rain drips The Red window
I 've been beaten by the wind all my life
Dream becomes a ray of sunshine in the distance
See you with the wind

The smile on your chrysanthemum is yellow
My mind is quiet
North Wind, night, and night, your shadows are constantly cut
In vain, I am alone in the lake
</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 = "JavaScript">

VaR RNG = txtbox. createTextRange ();

Function findtext (STR)
{
If (STR = "")
Return;
// Define 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 the new start point after the selected text is skipped.
RNG. movestart ("character", num );
RNG. moveend ("character", txtbox. value. Length );
// Select text after searching
If (RNG. findtext (STR ))
RNG. Select ();
// 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)
If (RNG. Text! = Str)
{
Alert ("Search completed ");
RNG = txtbox. createTextRange ();
}
}

</SCRIPT>

5. 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.

Example 4:

<SCRIPT>
Function getparelem ()
{
VaR RNG = Document. selection. createRange ();
VaR Container = RNG. parentelement ();
Alert (container. tagname );
}
</SCRIPT>

This is the text that only belongs to the body.
<Div> This is the text contained in the DIV </div>
<P> This is the text contained in P </P>

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.