vue项目中在可编辑div光标位置插入内容的实现代码
程序员文章站
2022-04-09 16:27:44
vue项目中在可编辑div光标位置插入内容
html:
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光标位置插入内容的实现代码,希望对大家有所帮助
上一篇: Vue学习之常用指令实例详解
下一篇: vue图片上传组件使用详解