有没有办法通过代码select CKEditor 5 的所有内容?
Is there any way to select all the content of CKEditor 5 by code?
我想 select 编辑器的所有内容并在 CKEditor 5 中对其执行命令。
可以吗?
最短的代码是这样的:
const root = doc.getRoot();
editor.model.change( writer => {
writer.setSelection( root, 'in' );
// Execute command in the same change() block to have just one undo step.
editor.execute( 'someCommand' );
} );
它使用模型作者的setSelection()
。
然而,这并不完全正确。上面的代码尝试进行以下选择:
<$root>[<paragraph>X</paragraph><paragraph>Y</paragraph>]</$root>
而你想要的是:
<$root><paragraph>[X</paragraph><paragraph>Y]</paragraph></$root>
那是因为选择应该始终坚持文本(或 object elements)。
幸运的是,由于版本 11.0.0 CKEditor 5 验证了选择的位置,因此它会自动移动到正确的位置。
在 v11.0.0 之前或者如果你想真正正确,你需要实施更长的解决方案,finds the right selection positions 在内容的开头和结尾:
import Range from '@ckeditor/ckeditor5-engine/src/model/range';
const doc = editor.model.document;
const root = doc.getRoot();
editor.model.change( writer => {
const range = Range.createIn( root );
const startRange = editor.model.schema.getNearestSelectionRange( range.start );
const endRange = editor.model.schema.getNearestSelectionRange( range.end );
writer.setSelection( new Range( startRange.start, endRange.end ) );
// Execute command in the same change() block to have just one undo step.
editor.execute( 'someCommand' );
} );
我想 select 编辑器的所有内容并在 CKEditor 5 中对其执行命令。
可以吗?
最短的代码是这样的:
const root = doc.getRoot();
editor.model.change( writer => {
writer.setSelection( root, 'in' );
// Execute command in the same change() block to have just one undo step.
editor.execute( 'someCommand' );
} );
它使用模型作者的setSelection()
。
然而,这并不完全正确。上面的代码尝试进行以下选择:
<$root>[<paragraph>X</paragraph><paragraph>Y</paragraph>]</$root>
而你想要的是:
<$root><paragraph>[X</paragraph><paragraph>Y]</paragraph></$root>
那是因为选择应该始终坚持文本(或 object elements)。
幸运的是,由于版本 11.0.0 CKEditor 5 验证了选择的位置,因此它会自动移动到正确的位置。
在 v11.0.0 之前或者如果你想真正正确,你需要实施更长的解决方案,finds the right selection positions 在内容的开头和结尾:
import Range from '@ckeditor/ckeditor5-engine/src/model/range';
const doc = editor.model.document;
const root = doc.getRoot();
editor.model.change( writer => {
const range = Range.createIn( root );
const startRange = editor.model.schema.getNearestSelectionRange( range.start );
const endRange = editor.model.schema.getNearestSelectionRange( range.end );
writer.setSelection( new Range( startRange.start, endRange.end ) );
// Execute command in the same change() block to have just one undo step.
editor.execute( 'someCommand' );
} );