富贵资源网 Design By www.hznty.com

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

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com