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

网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要介绍了vue项目中在可编辑div光标位置插入内容的实现代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

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光标位置插入内容的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!
如果你觉得本文对你有帮助,欢迎网络推广网站推广转载,烦请注明出处,谢谢!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by