【问题标题】:CKEditor 5 copy selected content from one editor to anotherCKEditor 5 将选定内容从一个编辑器复制到另一个编辑器
【发布时间】:2019-01-30 06:48:53
【问题描述】:

我在屏幕上有两个编辑器,一个是只读的。我想要做的是允许用户从只读编辑器中选择内容并通过单击按钮将其粘贴到另一个的当前位置。 (逻辑可能会操纵文本,这是我不想使用系统剪贴板的原因之一。)

到目前为止,我拥有能够粘贴文本的功能,如下所示。 (我正在使用 Angular 包装器,它解释了 CKEditorComponent 参考的存在。

  doPaste(pasteEvent: PasteEvent, editorComponent: CKEditorComponent) {
    const editor = editorComponent.editorInstance;
    editor.model.change(writer => {
      writer.insertText(pasteEvent.text, editor.model.document.selection.getFirstPosition() );
    });
}

我无法从文档中找到如何提取所选文本。到目前为止我所拥有的是:

  clickPasteSelectedPlain(editorComponent: CKEditorComponent) {
    const editor = editorComponent.editorInstance;
    const selection = editor.model.document.selection;
    console.log('clickPasteAll selection', selection);
    console.log('clickPasteAll selectedcontent', editor.model.document.getSelectedContent);
  }

选择似乎会根据编辑器视图中的选择而改变。 getSelectedContent 函数未定义。如何获取内容?

【问题讨论】:

  • 我认为您可以使用this answer 提取选定的文本。
  • @oleq 我看到了那个答案,但我打了折扣,因为编辑器中没有 getSelection() 函数。至少在当前版本中没有。

标签: ckeditor5


【解决方案1】:

经过一番摸索,我想出了如何做到这一点。我将在这里记录它,以期它可以帮助其他人避免我经历的发现过程。

在源文档中,我有一个 ckeditor 元素,如下所示:

  <div *ngIf="document">
    <ckeditor #ckEditor
              [editor]="Editor" [config]="ckconfig" [disabled]="true"
              [(ngModel)]="document.text"></ckeditor>
    <button mat-flat-button (click)="clickPasteSelectedPlain(ckEditor)">Paste Selected Text Plain</button>
  </div>

在组件中click事件调用的函数是这样的:

  @Output() paste = new EventEmitter<PasteEvent>();
     ...
  clickPasteSelectedPlain(editorComponent: CKEditorComponent) {
    const editor = editorComponent.editorInstance;
    this.paste.emit({
      content: editor.model.getSelectedContent(editor.model.document.selection),
      obj: this.document,
      quote: false
    });
  }

PasteEvent 被定义为一个导出的interface,为了节省篇幅我将在此省略。 content 键将引用 DocumentFragment

请注意,我将 CKEditorComponent 作为参数传递。您也可以通过 Angular @ViewChild 声明访问它,但请注意我的 ckeditor 位于 *ngIf 结构中。我认为这在 Angular 6 中效果很好,但在过去,当目标有条件地位于 DOM 中时,我在使用 @ViewChild 引用时遇到了困难。此方法始终有效,但请使用您想要的任何方法。

emit 触发的事件使用如下所示的方法进行处理:

  doPaste(pasteEvent: PasteEvent, editorComponent: CKEditorComponent) {
    const editor = editorComponent.editorInstance;
    editor.model.insertContent(pasteEvent.content);
  }

由于内容是DocumentFragment,因此粘贴操作将包括所选源中包含的所有格式和文本属性。但仅此而已。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-31
    • 2011-11-03
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多