首页 > 解决方案 > 如何在 CKEditor5 中设置选择?

问题描述

在编辑器中设置文本后,我需要将焦点设置到文本的末尾。怎么做?我无法理解

editor.setData('text');
editor.editing.view.focus(); // focus to set the beginning, but on the end

示例:https ://jsfiddle.net/ogm5s6k7/1/

// Editor configuration.
ClassicEditor
  .create( document.querySelector( '#editor' ))
  .then( editor => {
  window.editor = editor;
})
  .catch( error => {
  console.error( error );
});

document.getElementById('focusSet').onclick = function(e) {
  window.editor.setData('text');
  window.editor.editing.view.focus();
};
<script src="https://cdn.ckeditor.com/ckeditor5/11.1.0/classic/ckeditor.js"></script>
<div id="editor">
  <p>Editor content goes here.</p>
</div>
<br>
<button id="focusSet">Focus</button>

标签: javascriptckeditor5

解决方案


要在 CKE5 中设置选择,您需要在可以访问编写器的“更改块”中进行:

editor.model.change( writer => {
    writer.setSelection( ... );
} );

有几种设置选择的方法,请参阅文档:https ://ckeditor.com/docs/ckeditor5/latest/api/module_engine_model_writer-Writer.html#function-setSelection

基本上,您在设置选择时需要一些参考。例如,如果要在给定模型节点之后设置它,则需要对该节点的引用,然后可以像这样使用它:

writer.setSelection( myNode, 'after' );

如果要将其设置在内容的末尾,可以使用文档根目录:

writer.setSelection( editor.model.document.getRoot(), 'end' );

推荐阅读