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