在一个非Vue项目构建的、仅是普通的JavaScript项目里,只是简单地在页面引入了quill.js、vue-quill-editor.js、vue.js。 1. 需要实现在vuequilleditor中粘贴文本时,将粘贴的富文本转换文纯文本,并插入到光标所在位置。 2. 如果光标选中了部分内容,需要将选中的内容替换为粘贴文本。 3. 插入文本后,需要修改光标位置到插入文本的后面 4. 即使当前光标所在的位置(选中的文本)带有css样式,粘贴后的文本也不能带有样式。 Vue.use(window.VueQuillEditor) var toolbarOptions = [ ['bold', 'underline'], [{ 'color': ['blue', 'red', 'black'] }], ['link'], ['clean'] ] var main = new Vue({ el: "#main", data: { QuillEditors: [], editorOption: { scrollingContainer: null, modules: { toolbar: toolbarOptions }, theme: 'snow' }, }, methods: { } }) 我尝过使用mounted函数,监听‘paste’事件,然后获取剪切板内容的文本格式(text/plain),再调用quill的insertText方法将文本内容插入。 但是插入后,文本内容会受到 插入index所在的delta的样式的影响? 同样,删除时使用deleteText、insertText方法,结果也都不理想。 * * * 经过maxkiicc大佬的帮助,我已经解决了 1. 需要实现在vuequilleditor中粘贴文本时,将粘贴的富文本转换文纯文本,并插入到光标所在位置。 2. 插入文本后,需要修改光标位置到插入文本的后面 3. 即使当前光标所在的位置(选中的文本)带有css样式,粘贴后的文本也不能带有样式。 尚未解决的问题为: 2. 如果光标选中了部分内容,需要将选中的内容替换为粘贴文本。 问题描述: 如果用光标选中一部分内容,然后再粘贴,会发现粘贴的内容被删除了光标选中文本长度的内容。 比如: 当前内容为:1234 光标选中文本:23 要粘贴的内容:index 得到的结果:1dex4 Vue.use(window.VueQuillEditor) var toolbarOptions = [ ['bold', 'underline'], [{ 'color': ['blue', 'red', 'black'] }], ['link'], ['clean'] ] var main = new Vue({ el: "#main", data: { QuillEditors: [], editorOption: { scrollingContainer: null, modules: { toolbar: toolbarOptions }, theme: 'snow' }, }, mounted () { var quill = this.$refs.myQuillEditor.quill quill.root.addEventListener('paste', function (e) { e.preventDefault() const clipboardData = e.clipboardData || window.clipboardData const pastedText = clipboardData.getData('text/plain') requestAnimationFrame(() => { const pasteLength = pastedText.length const index = quill.selection.savedRange.index const length = quill.selection.savedRange.length // retain delete的index不能等于0 if (index === 0) { if (length !== 0) { quill.updateContents([ { insert: pastedText, }, { delete: length } ]) } else { quill.updateContents([ { insert: pastedText, }, ]) } } else { if (length !== 0) { quill.updateContents([ { retain: index, }, { insert: pastedText, }, { delete: length } ]) } else { quill.updateContents([ { retain: index, }, { insert: pastedText, }, ]) } } // 挪动光标到复制文本后 setTimeout(() => { quill.setSelection(index + pasteLength, 0) }, 0) }) }) } })