Use of textrange and range objects

Source: Internet
Author: User

The description of the textrang object and the range object is well written. Unfortunately, the HTML code format of the example in this article is too messy and difficult to read. Here we will sort it out to facilitate future reading.
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

HTML code

 

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en"> <HTML> 

 

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.

Search for strings in text

HTML code

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en"> <HTML> 

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:

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.

Obtain the DOM object of the selected text with the cursor

HTML code

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en"> <HTML> 

Range object

The range object indicates the continuous range area of the document. For example, you can drag the selected area with the mouse in the browser window.

Dom standard range object

Use textrange object in IE

Common methods for establishing range objects

In addition to the standard establishment methods in the above documents, most of the methods are as follows:

Standard DOM:

VaR range = Window. getselection (). getrangeat (0 );

IE:

VaR range = Document. selection. createRange ();

Note: The standard DOM is used to obtain the selection object from the window, While IE is used to obtain the selection object from the document object.

The standard DOM range object (DOM rang) differs greatly from the textrange object (textrange) of IE in the operation mode. It can be said that Dom range is controlled based on the DOM structure, textrange is based on the byte control of the text node. Read the following example to better understand the operation modes of the two. The range object mentioned below refers to the selection and modification (designMode = on contenteditable = true) operation in the HTML structure. The operation in textarea is simpler than this, it is not the current research environment.

For details about the methods and attributes of the range object, refer to the relevant API documentation listed above.

1. Select the region to obtain text from the region.

Select a textrange Region

The textrange object mainly controls the selection of the region using the following methods: movestart moveend move

These three functions use the same parameter Syntax: FN (Sunit [, icount])

The first parameter refers to the unit of movement. The following parameters can be used: character, word, sentence, and textedit)

The second parameter refers to the number unit of movement. A negative number is moved before the position, and a positive number is moved after the position.

Character is generally used in actual development. Several other parameters are different from the expected position when editing the Chinese environment and HTML.

Example 1: textrange selects the first 4 characters of the cursor

The Code is as follows:

VaR Rg = Document. selection. createRange ();

RG. movestart ("character",-4 );

RG. Select (); // select the text area explicitly. You can obtain the selected content without calling this function.

VaR text = RG. Text; // obtain the selected text

VaR htmltext‑rg.html text; // obtain the HTML code of the selected text

Use rg.html text to obtain the HTML code of the selected text, but the results are not satisfactory,

For example, <B> AAAA </B> BB, When you select AABB, .html Tex returns <B> AA </B> BB instead of AA </B> BB.

Other common location control functions:

Collapse: Pre-and Post-selection points. True indicates the start point and false indicates the end point.

Movetopoint: move the cursor to the coordinate movetobookmark: Move to the bookmarks.

Selection of Dom range regions

The selection area of the DOM range object mainly uses the DOM node as the coordinate, and all the boundary moving and region selection functions are based on the DOM node as the reference.

Setend () setstart () is a function that controls the front and back boundary points of a range,

There are two parameters. The first parameter is the DOM node, and the second parameter is the offset. this parameter is different from that in textrange. Move, and is the offset relative to the DOM node.

For example, if the node1 nodevalue of a text node is aaabbbccc, and setstart (node1, 3), set the start position between characters a and B.

So how can we select the first four characters of the cursor like Example 1? We need to know several attributes of the DOM range object:

The endcontainer contains the DOM node of the end point of the range.

End Point Position in endoffset endcontainer.

Startcontainer contains the DOM node of the start point of the range.

Start point position in startoffset startiner iner.

Example 2: Dom range selects the first 4 characters of the cursor

The Code is as follows:

VaR Rg = Window. getselection (). getrangeat (0 );

RG. setstart (RG. startcontainer, RG. startOffset-4); // obtain the node and offset of the current range Strat, which is calculated as a parameter

// After setstart is called, it is explicitly selected, which is different from textrange.

VaR text = RG. tostring (); // obtain the selected text

RG. Collapse (false); // The collapse function is the same as textrange. collapse.

In Example 2, the range selection operation applies to a single text content. If it is HTML content, further calculation is required to obtain it correctly, in general, it is troublesome to select relative ranges in complex Dom structures.

In addition, Dom range does not directly obtain the HTML code of the selected content. In the HTML editable state, you can use the surroundcontents () method to wrap the content with a tag such as span and then obtain the content through innerhtml, however, when you select a range boundary point in the HTML start and end tags (for example, <A> 123 </a> boundary point in the tag), an exception is thrown.

The following is the complete code for testing, including the code for example 1 and example 2, and an HTML editable area for testing.

The Code is as follows:

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en"> <HTML> 

2. Insert text

Textrange insert text

Using textrang to insert text is relatively simple. You can directly insert HTML code by calling the pastehtml () method.

Insert text into Dom range

Using Dom range to insert text is relatively complicated. Dom range objects are inserted using the insertnode () method. However, insertnode inserts a node at the beginning of range, and the parameter is a node rather than a string, we can insert a text node. If you use document. createtextnode creates a text node. HTML tags in the text are automatically converted, but spaces are a special case and are not automatically converted to. This makes it a headache when developing code indentation, the final solution is to use rang. createcontextualfragment. This method is not found in the document, but is supported by multiple browsers. This method returns a documentfragment pair

Image. The following is the sample code:

Example 3:

JS Code

The Code is as follows:

VaR Rg = Window. getselection (). getrangeat (0 );

VaR fragment = RG. createcontextualfragment (STR );

RG. insertnode (fragment );

Although this code inserts text, the cursor position is before the text is inserted, because "insertnode is inserting a node at the beginning of range", then we implement cursor control, this requires setting the location of the range object and updating the range of the selection object. The Code is as follows:

Example 4:

JS Code

The Code is as follows:

VaR selection = Window. getselection ();

VaR Rg = selection. getrangeat (0 );

VaR fragment = RG. createcontextualfragment (STR );

VaR olastnode = fragment. lastchild; // obtain the end position of documentfragment

RG. insertnode (fragment );

RG. setendafter (olastnode); // sets the end position.

RG. Collapse (false); // The merge range ends with the end.

Selection. removeallranges (); // clear range

Selection. addrange (RG); // sets the range

The following is an example of code indent: When you press the tab key, four spaces are inserted at the current position to solve the problem that you cannot enter a tab during editing. In practice, the functions include multi-line indentation and automatic indentation.

The Code is as follows:

 

<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en"> <HTML> 

 

3. Replace

The selection and insertion methods described in this article can be used to complete the replacement function. The pastehtml method in textrange is simple and replaces the selected text in the original range. The insertnode in Dom range does not delete the selected content in the original range, you must call deletecontents () to delete the selected content first.

From: http://baike.baidu.com/view/1938779.htm

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.