quilljs富文本编辑器粘贴板跳跃问题

quill富文本编辑器复制粘贴内容时,焦点跳跃到顶部的解决方案。

引入相关组件:

import Delta from "quill-delta";

重写粘贴板:

  const Clipboard = Quill.import("modules/clipboard");

  class CustomClipboard extends Clipboard {
   onPaste(e) {
    // get current page offset before paste
    const top = window.pageYOffset;
    const left = window.pageXOffset;

    if (e.defaultPrevented || !this.quill.isEnabled()) return;
    let range = this.quill.getSelection();
    let delta = new Delta().retain(range.index);
    this.container.style.top =
     (
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop ||
      0
     ).toString() + "px";
    this.container.focus();
    setTimeout(() => {
     this.quill.selection.update(Quill.sources.SILENT);
     delta = delta.concat(this.convert()).delete(range.length);
     this.quill.updateContents(delta, Quill.sources.USER);
     this.quill.setSelection(
      delta.length() - range.length,
      Quill.sources.SILENT
     );
     let bounds = this.quill.getBounds(
      delta.length() - range.length,
      Quill.sources.SILENT
     );
     this.quill.scrollingContainer.scrollTop = bounds.top;

     // scroll window to previous position after paste
     window.scrollTo({ top, left });
    }, 1);
   }
  }

注册新的粘贴板:

Quill.register("modules/clipboard", CustomClipboard, true);

创建Quill编辑器对象:

 var quill = new Quill("#editor", {
   modules: {
    toolbar: toolbarOptions,
    history: {
     delay: 2500,
     userOnly: true
    }
   },
   theme: "snow"
  });

如果未能解决问题,参考相关问题列表