移动端 可输入div 在文字中间插入表情

移动端 可输入div 在文字中间插入表情_第1张图片

 //调用
    if(thatInput.hasClass("flag") && window._range) {
            insertContent(imgSrc);
        } 


    //===========================光标位置
    
    $(".textarea").blur(function(){
        $(this).addClass("flag");
        saveRange();
    });
    //保存光标位置
   function saveRange() {
       var selection = window.getSelection ? window.getSelection() : document.selection;
       if(!selection.rangeCount) return;
       var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);
       window._range = range;
   }
   //插入内容
   function insertContent(str) {
       var selection, range = window._range;
       if(!window.getSelection) {
           range.pasteHTML(str);
           range.collapse(false);
           range.select();
       } else {

           selection = window.getSelection ? window.getSelection() : document.selection;
           range.collapse(false);
           var hasR = range.createContextualFragment(str);
           var hasR_lastChild = hasR.lastChild;
           while(hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") {
               var e = hasR_lastChild;
               hasR_lastChild = hasR_lastChild.previousSibling;
               hasR.removeChild(e);
           }
           
           range.insertNode(hasR);
           
           if(hasR_lastChild) {
               range.setEndAfter(hasR_lastChild);
               range.setStartAfter(hasR_lastChild);
           }
           selection.removeAllRanges();
           selection.addRange(range);
       }

   };

 

 转自https://segmentfault.com/q/1010000010590998

你可能感兴趣的:(JavaScript知识点)