Home  >  Article  >  Web Front-end  >  Commonly used cross-browser operations on javascript Range objects_javascript skills

Commonly used cross-browser operations on javascript Range objects_javascript skills

PHP中文网
PHP中文网Original
2016-05-16 18:45:101011browse

Recently, I have been frequently exposed to Range objects in the process of developing online code editors. Due to cross-browser requirements, IE TextRange objects and standard Dom Range objects are used.

The developed functions mainly involve instant code coloring (CodeColoring) and syntax hints (CodeHints). Problems in function development will be summarized or source code will be provided later.
The following are examples and summaries of personal understanding of the Range object and common operations:
Range Object
The Range object represents the continuous range area of ​​the document, such as the user dragging the selected area with the mouse in the browser window .
dom standard Range object
http://www.php.cn/
Use TextRange object in IE
http://www.php.cn/
Commonly used creation of range objects Methods
In addition to the standard establishment methods in the above documents during development, most of the
standard doms are established as follows:
var range=window.getSelection().getRangeAt(0);
ie:
var range=document.selection.createRange();
Note: Standard DOM obtains the selection object from the window, while IE obtains it from the document object.
The standard dom range object (hereinafter referred to as dom rang) and ie's TextRange object (hereinafter referred to as TextRange) are very different in the operation mode. It can be said that dom range is controlled based on the dom structure, and TextRange is based on the text node character Section control, reading the following examples will better understand the operation modes of these two. The range object mentioned below refers to the selection and change operations in the html structure (designMode=on contentEditable=true state). The operation in the textarea is simpler than this and is not the current research environment.
For the specific methods and properties of the range object, please check the relevant api documents listed above. The following is an explanation of the common functions in the actual development process
1. Region selection to obtain the text in the region
Region selection of TextRange
The TextRange object mainly uses the following methods to control the selection of the area: moveStart moveEnd move
These three functions use the same parameter syntax: fn(sUnit [, iCount])
The first parameter refers to the unit of movement, which can Parameters used: character (character), word (word), sentence (paragraph), textedit (entire editing area)
The second parameter refers to the unit of movement. Negative numbers move to the front of the position, and positive numbers move to the position. Then move.
Character is generally used in actual development. Several other parameters deviate from the expected position in the Chinese environment and HTML editing.
Example 1: TextRange selects the 4 characters before the cursor

var rg=document.selection.createRange();
rg.moveStart("character",-4);
rg. select();//Explicitly select the text area, you can get the selected content without calling this function
var text=rg.text;//Get the selected text
var htmlText=rg.htmlText;// Get the html code of the selected text


Use rg.htmlText to get the html code of the selected text, but the result is not satisfactory,
such as: aaaa bb, when selecting the aabb segment, .htmlTex returns aabb instead of aabb
Other commonly used position control functions:
collapse: Select points before and after merging, true is the starting point, false is the ending point.
moveToPoint: Move the cursor to the coordinates moveToBookmark: Move to the bookmark.
Region selection of dom range
The dom range object selection area mainly uses the dom node as the coordinate. All boundary movement and area selection functions are based on the dom node as a reference.
setEnd() setStart() is the control A function of the position of the front and back boundary points of the range,
has two parameters, the first parameter is the dom node, and the second parameter is the offset. This parameter is different from TextRange.move, it is relative to The offset of the dom node.
For example: there is a text node node1 nodeValue is aaabbbccc, setStart(node1,3) will set the starting position between characters a and b
Then how to select the 4 characters before the cursor like Example 1, this needs to be understood Several attributes of the dom range object:
endContainer contains the dom node of the end point of the range.
endOffset The end point position in endContainer.
startContainer contains the dom node of the start point of the range.
startOffset The starting point position in startContainer.
Example 2: dom range selects the 4 characters before the cursor

var rg=window.getSelection().getRangeAt(0);
rg.setStart(rg.startContainer,rg.startOffset-4 );//Get the node and offset of the current range strat, and use it as a parameter after calculation
//It is explicitly selected after calling setStart, which is different from TextRange
var text=rg.toString();// Get the selected text
rg.collapse(false); //collapse function is the same as TextRange.collapse


The range selection operation in Example 2 is suitable for a single text content. If it is HTML content, further calculations are needed to get it correctly. Generally speaking, it is more troublesome to select relative ranges of dom range in complex dom structures. of.
In addition, there is no direct way for dom range to 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 the selection range boundary points are within the html start and end tags (such as: 123The boundary point is within the a tag) will throw an exception.
The following is the complete code for testing, including the code for Example 1 and Example 2 and an html editable area for testing.




New Document



< /p>




2. Insert text
TextRange Insert text
Using TextRang to insert text is relatively simple. Simply call the pasteHTML() method to directly insert html code.
Insert text with Dom Range
Inserting text using Dom Range is relatively complicated. The Dom Range object uses the insertNode() method to implement insertion, but insertNode inserts a node at the beginning of the Range, and the parameter is a node instead of a string. , we can achieve this by inserting text nodes. If we use document.createTextNode to create a text node, the HTML tags in the text will be automatically converted, but spaces are a special case and will not be automatically converted to . This gives me a headache when developing code indentation. , the final solution is to use Rang.createContextualFragment. Although this method is not found in the document, it has been tested that multiple browsers support this method. This method returns a DocumentFragment object
. The following is the sample code:
Example 3:
Js code

Copy code The code is as follows:


var rg = window. getSelection().getRangeAt(0);
var fragment = rg.createContextualFragment(str);
rg.insertNode(fragment);


Although this code implements insertion text, but the cursor position is before the text is inserted, because "insertNode inserts a node at the beginning of the Range". Next, we implement cursor control, which requires setting the position of the Range object and updating the Range of the Selection object. Code As follows:
Example 4:
Js code

Copy code The code is as follows:


var selection=window.getSelection();
var rg=selection.getRangeAt(0);
var fragment = rg.createContextualFragment(str);
var oLastNode = fragment.lastChild ; //Get the end position of DocumentFragment
rg.insertNode(fragment);
rg.setEndAfter(oLastNode);//Set the end position
rg.collapse(false);//Merge range to the end
selection.removeAllRanges();//Clear range
selection.addRange(rg);//Set range


The following is part of the code for a code indentation function as an example : When pressing the tab key, 4 spaces will be inserted at the current position to solve the problem of not being able to enter tab during editing. Features in practical applications include multi-line indentation and automatic indentation.

Copy code The code is as follows:





New Document


< SCRIPT LANGUAGE="JavaScript">






3. Replace
The selection and insertion methods introduced comprehensively can complete the replacement function. TextRange is relatively simple and the pasteHTML method will replace the text selected in the original Range. The insertNode of Dom Range will not delete the selected content in the original range. You need to call the deleteContents() method to delete it first. Select content.
The above introduces the commonly used area selection, text insertion and replacement operations using the Range object. I hope it will be helpful when you develop an online editor. Please forgive me for the roughness.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn