HTML Rich Text Editor--general methods for inserting various DOM elements such as text images inside the editor

Source: Internet
Author: User

Problematic insertion Scenarios

<! DOCTYPE html>"en">"UTF-8"> <title></title> <style> #edit {height:500px;width:500px;border:1px solid red;} </style>"Edit"Contenteditable></div><input type="text"Id="Emojiinput"><button id="Sendemoji"> Send Emoticons </button><script>varSendemoji = document.getElementById ('Sendemoji')    //define the last cursor object    varLasteditrange; //edit box Click eventdocument.getElementById ('Edit'). onclick =function () {//get selected object        varSelection =getselection ()//set the last cursor objectLasteditrange = Selection.getrangeat (0)    }    //edit box Key Bounce Eventdocument.getElementById ('Edit'). onkeyup =function () {//get selected object        varSelection =getselection ()//set the last cursor objectLasteditrange = Selection.getrangeat (0)    }    //Emoji Click eventdocument.getElementById ('Sendemoji'). onclick =function () {//get edit Box Object        varEdit = document.getElementById ('Edit')        //Get Input Box object        varEmojiinput = document.getElementById ('Emojiinput')        //edit box Set FocusEdit.focus ()//get selected object        varSelection =getselection ()//determine if a last cursor object exists        if(lasteditrange) {//The last cursor object exists, the selected object clears all cursors and adds the state before the last cursor is restoredselection.removeallranges () Selection.addrange (Lasteditrange)}//determines whether the selected object range is an edit box or a text node        if(Selection.anchorNode.nodeName! ='#text') {            //if it is an edit box range. Create an emoticon text node to insert            varEmojitext =document.createTextNode (Emojiinput.value)if(Edit.childNodes.length >0) {                //if the child element of the text box is greater than 0, it indicates that there are other elements, then the expression node is inserted by position                 for(vari =0; i < edit.childNodes.length; i++) {                    if(i = =selection.anchoroffset) {edit.insertbefore (Emojitext, edit.childnodes[i]) }                }            } Else {                //or insert an expression element directlyedit.appendchild (emojitext)}//Create a new cursor object            varRange =Document.createrange ()//the scope of the cursor object is defined as the new expression noderange.selectnodecontents (Emojitext)//The maximum length of the position of the cursor in the expression nodeRange.setstart (Emojitext, Emojitext.length)//causes the cursor to begin and overlap the cursor endRange.collapse (true)            //clears all cursor objects for the selected objectselection.removeallranges ()//Insert a new Cursor objectSelection.addrange (range)}Else {            //Debugger; //gets the cursor object first if it is a text node            varRange = Selection.getrangeat (0)            //gets the range-scoped object of the cursor object, which is generally the Textnode object            varTextnode =Range.startcontainer; //Get cursor Position            varRangestartoffset =Range.startoffset; //text node inserts new emoticon content at cursor positionTextnode.insertdata (Rangestartoffset, Emojiinput.value)//move the cursor to the original position plus the length of the new contentRange.setstart (Textnode, Rangestartoffset +emojiInput.value.length)//cursor start and cursor end overlapRange.collapse (true)            //clears all cursor objects for the selected objectselection.removeallranges ()//Insert a new Cursor objectSelection.addrange (range)}//record the last cursor object anywayLasteditrange = Selection.getrangeat (0)    }</script></body>View Code

Questions to consider when inserting,

The first original container has text content, now inserted in the middle of the text content DOM elements, the above method is not resolved,

Position of the newly inserted element after the second insert

The solution of OK

/** * In the input area to insert a variety of East General * @param HTML*/function insertimg (HTML) {varDthis = $ ("#input-content")[0]; varSEL =getselection (); if(window.getselection) {//IE9 and Non-ieSEL =window.getselection (); if(Sel.getrangeat &&sel.rangecount) {range= Sel.getrangeat (0);            Range.deletecontents (); varEl = Document.createelement ('Div'); El.innerhtml=html; varFrag =document.createdocumentfragment (), node, lastnode;  while(node =el.firstchild)) {Lastnode=frag.appendchild (node);            } range.insertnode (Frag); if(lastnode) {range=Range.clonerange ();                Range.setstartafter (Lastnode); Range.collapse (true);                Sel.removeallranges ();            Sel.addrange (range); }        }    } Else if(document.selection && Document.selection.type! ='Control') {$ (dthis). focus ();//in non-standard browsers, let the div you need to insert HTML get the focusIerange = Document.selection.createRange ();//Get cursor Positionierange.pastehtml (HTML);//Insert HTML at cursor position if you just insert text then it's fus.text= "..."$ (dthis). focus (); }}

HTML Rich Text Editor--general methods for inserting various DOM elements such as text images inside the editor

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.