The correct method is to correctly use the Selection object and Range object to insert text or nodes at the current position of the cursor. However, these two objects use different methods in IE and standard DOM.
Idea: first obtain the user's constituency (the current position of the cursor can be understood as the constituency with the same starting position and ending position ). Then, convert the Selection object to the Range object. The purpose is to insert content using the Range object method. Finally, move the cursor to the end of the inserted content.
01
Var sel = win.doc ument. selection; // IE
02
Var sel = win. getSelection (); // DOM
03
04
Var range = sel. createRange (); // under IE
05
Var range = sel. getRangeAt (0); // under the DOM
06
07
If (range. startContainer) {// under DOM
08
Sel. removeAllRanges (); // delete all ranges in Selection
09
Range. deleteContents (); // clear the content in the Range.
10
// Obtain the first html node in the Range.
11
Var container = range. startContainer;
12
// Get the displacement of the starting point of the Range.
13
Var pos = range. startOffset;
14
// Create an empty Range
15
Range = document. createRange ();
16
// Insert content
17
Var cons = win.doc ument. createTextNode (",:),");
18
19
If (container. nodeType = 3) {// if it is a TextNode
20
Container. insertData (pos, cons. nodeValue );
21
// Change the cursor position
22
Range. setEnd (container, pos + cons. nodeValue. length );
23
Range. setStart (container, pos + cons. nodeValue. length );
24
} Else {// if it is an HTML Node
25
Var afternode = container. childNodes [pos];
26
Container. insertBefore (cons, afternode );
27
28
Range. setEnd (cons, cons. nodeValue. length );
29
Range. setStart (cons, cons. nodeValue. length );
30
}
31
Sel. addRange (range );
32
} Else {// IE
33
Var cnode = range. parentElement ();
34
While (cnode. tagName. toLowerCase ()! = "Body "){
35
Cnode = cnode. parentNode;
36
}
37
If (cnode. id & cnode. id = "rich_txt_editor "){
38
Range. pasteHTML (",:),");
39
}
40
}
41
Win. focus ();
Differences between innerHTML and pasteHTML
InnerHTML is an attribute that can be used to obtain or set the HTML content of the element. It can be used by any element that can contain HTML subnodes.
PasteHTML () is a method that replaces text or HTML in the specified text area. This method must be applied to a createTextRange () or document. selection. on the region created by createRange ()
1
Var oRange = document. selection. createRange ();
2
If (oRange. text! = ''){
3
Var oHtml = '<a href = "#" target = _ blank> oRange. text </a> ';
4
ORange. pasteHTML (oHtml );
5
}
From JSON