vue项目中在可编辑div光标位置插入内容

HTML

<div class="mouse-move fl f12 h22 lh22 mg-r5 sms-item"
   @dragstart="dragStart($event, item.labelName)"
   draggable='true'
 v-for="(item, index) in modelCommonList"
   :key="index"
   @click="dropRelease($event, item.labelName)">
   {{item.labelName}}
 </div>
<div contenteditable="true"
   @drop="dropRelease($event)"
   @dragover="allowDrop($event)"
   ref="smsContent"
   class="border-r4 f12 h100 pd-tb10 pd-lr10 overflow-scroll-y editable-div"
   id="smsContent">
</div>

methods:

 insertHtmlAtCaret(html) {
    let sel, range;
    if (window.getSelection) {
      // IE9 and non-IE
      sel = window.getSelection();
      if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();
        let el = document.createElement("div");
  el.appendChild(html)
        var frag = 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") {
      // IE < 9
      document.selection.createRange().pasteHTML(html);
    }
  },
 //刚开始拖拽可选字段
  dragStart(event, name) {
    event = event || window.event;
    this.dragging = name; //str
    event.dataTransfer.setData(" ", " "); //for firefox
  },
  //阻拦默认设置恶性事件
  allowDrop(event) {
    let e = event || window.event;
    if (e && e.preventDefault) {
      e.preventDefault();
    } else {
      window.event.returnValue = false;
    }
  },
  //拖拽到特定位置并释放出来
  dropRelease(event, nodeValueName) {
    event = event || window.event;
    event.preventDefault();
    let textNode = document.createElement('input');
    textNode.className = 'mg-lr5 enabledTag';
    textNode.type = 'button';
    textNode.value = this.dragging || nodeValueName;
    this.insertHtmlAtCaret(textNode);
    this.dragging = '';
  },

小结

之上上述是我给大伙儿详细介绍的vue项目中在可编辑div光标位置插入内容的完成编码,期待对大伙儿有一定的协助,假如大伙儿有一切有意者帮我留言板留言,我会立即回应大伙儿的。在这里也特别感谢大伙儿对网址的适用!
如果你觉得文中对给你协助,热烈欢迎转截,劳烦标明出處,感谢!