前言:因项目需求,有一个富文本框,点击页面的插入姓名,会在富文本框内的鼠标处,插入姓名。
解决:利用window.getSelection() 来获取富文本框的焦点,并保存下来,在点击插入姓名时,在再那个焦点处插入。
EX:
注:因为项目是vue 写的,所以有些变量需要自己在data 里免定义
在富文本框内点击的时候保存一下焦点 this.sel ;isWang 是判断插入的时候,富文本框内点击一次,只能插一条数据
this.editor.customConfig.onfocus = () => { this.sel = window.getSelection(); this.range = this.sel.getRangeAt(0); this.range.deleteContents(); this.$set(this.get, 'isWang', true); }; this.editor.customConfig.onblur = (html) => { this.$set(this.get, 'isWang', false); };
// 插入的方法
insertHtmlAtCaret(html) { if (window.getSelection) { // IE9 and non-IE if (this.sel.getRangeAt && this.sel.rangeCount) { // Range.createContextualFragment() would be useful here but is // non-standard and not supported in all browsers (IE9, for one) var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } this.range.insertNode(frag); // Preserve the selection if (lastNode) { this.range = this.range.cloneRange(); this.range.setStartAfter(lastNode); this.range.collapse(true); this.sel.removeAllRanges(); this.sel.addRange(this.range); } } } else if (document.selection && document.selection.type != "Control") { // IE < 9 document.selection.createRange().pasteHTML(html); } },
// 点击插入姓名时插入的方法
insertName() { if (!this.get.isWang) { return false; } document.getElementById('editor').focus(); this.$set(this.insert, 'name', api.getUserName()); this.insertHtmlAtCaret('<span>' + this.insert.name + '</span>'); },