使用的富文本插件为VueQuill

html如下

 <QuillEditor
                        ref="quillEditor"
                        @click="handClick"
                        @textChange="handOnkeyup"
                        v-model:content="formState.content"
                        :options="options"
                    ></QuillEditor>

记录光标,关键就在这里

  // 最后一次的range对象
        let lastRange: any = null
        const handClick = () => {
            let selection: any = document.getSelection()
            // 保存最后的range对象
            lastRange = selection.getRangeAt(0)
        }
        const handOnkeyup = () => {
            let selection: any = document.getSelection()
            // 保存最后的range对象
            lastRange = selection.getRangeAt(0)
        }

点击内容插入,可自定义内容,其中e.name就是我传递进来的,可自行修改

 if (window.getSelection && lastRange) {
               let selection = window.getSelection();
                if (selection && selection.getRangeAt && selection.rangeCount) {
                    let addText = (dow: string) => {
                        lastRange.deleteContents();
                        var el = document.createElement("div");
                        el.innerHTML = dow;
                        var frag = document.createDocumentFragment(), node, lastNode;
                        while ((node = el.firstChild)) {
                            lastNode = frag.appendChild(node);
                        }
                        lastRange.insertNode(frag);
                        if (lastNode) {
                            lastRange = lastRange.cloneRange();
                            lastRange.setStartAfter(lastNode);
                            lastRange.collapse(true);
                            selection?.removeAllRanges();
                            selection?.addRange(lastRange);
                        }
                    }
                    
                    addText(`<span style="color:#1890FF;font-weight:bold">&nbsp;${e.name}</span>`)
                    // 防止影响后续文字颜色
                    addText(`<span style="color:#000;">&nbsp;</span>`)
                }
            }

 效果如下。点击上面的标签,插入内容到富文本中

Logo

前往低代码交流专区

更多推荐