This article describes how to insert a text label node at the cursor in JavaScript. It has good reference value. Next, let's take a look at it. This article mainly describes how to insert a text label node at the cursor in JavaScript. It has good reference value. Let's take a look at it with the small Editor.
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.
Var sel = win.doc ument. selection; // IE var sel = win. getSelection (); // DOM var range = sel. createRange (); // var range = sel under IE. getRangeAt (0); // if (range. startContainer) {// sel under DOM. removeAllRanges (); // delete all Range in Selection. deleteContents (); // clear the content in the Range // obtain the first html node var container = Range in the range. startContainer; // get the displacement of the Range starting point var pos = range. startOffset; // create an empty Range range = doc Ument. createRange (); // insert content var cons = win.doc ument. createTextNode (", :),"); if (container. nodeType = 3) {// if it is a TextNode container. insertData (pos, cons. nodeValue); // change the cursor position range. setEnd (container, pos + cons. nodeValue. length); range. setStart (container, pos + cons. nodeValue. length);} else {// if it is an HTML Node var afternode = container. childNodes [pos]; container. insertBefore (cons, afternode); range. se TEnd (cons, cons. nodeValue. length); range. setStart (cons, cons. nodeValue. length);} sel. addRange (range);} var cnode = range under else {// IE. parentElement (); while (cnode. tagName. toLowerCase ()! = "Body") {cnodecnode = cnode. parentNode;} if (cnode. id & cnode. id = "rich_txt_editor") {range. pasteHTML (", :),") ;}} win. focus ();
Differences between innerHTML and pasteHTML
InnerHTML is an attribute,You can obtain or set the HTML content of this element. You can use it for any element that can contain HTML subnodes.
PasteHTML () is a method,Replace text or HTML in the specified text area. This method must be applied to a region created by createTextRange () or document. selection. createRange ().
var oRange = document.selection.createRange(); if(oRange.text!=''){ var oHtml = 'oRange.text'; oRange.pasteHTML(oHtml); }
The preceding section details how to insert a text label node at the cursor in JavaScript. For more information, see other related articles in the first PHP community!