完整的解决方案将如下所示:
const pos = editor.document.selection.getFirstPosition();
// If you want to get the text up to the root's boundary:
// const posStart = Position.createAt( pos.root );
// const posEnd = Position.createAt( pos.root, 'end' );
// If you want to get the text up to the current element's boundary:
const posStart = Position.createAt( pos.parent );
const posEnd = Position.createAt( pos.parent, 'end' );
const rangeBefore = new Range( posStart, pos );
const rangeAfter = new Range( pos, posEnd );
let textBefore = '';
let textAfter = '';
// Range is iterable and uses TreeWalker to return all items in the range.
// value is of type TreeWalkerValue.
for ( const value of rangeBefore ) {
if ( value.item.is( 'textProxy' ) ) {
textBefore += value.item.data;
}
}
for ( const value of rangeAfter ) {
if ( value.item.is( 'textProxy' ) ) {
textAfter += value.item.data;
}
}
console.log( textBefore );
console.log( textAfter );
您在此处使用TreeWalker
来获取范围内的所有项目并将您在此处找到的文本代理字符串化。
请注意,您得到TextProxy
的是 s 而不是普通Text
节点,因为 tree walker 可能需要返回文本节点的一部分(如果范围在该文本节点的中间结束)。
编辑:要将内容字符串化为数据格式(因此 - 包括 HTML 标记,而不仅仅是文本),您需要使用一些不同的方法:
function doStuff( editor ) {
const pos = editor.document.selection.getFirstPosition();
const posStart = Position.createAt( pos.root );
const posEnd = Position.createAt( pos.root, 'end' );
const rangeBefore = new Range( posStart, pos );
const rangeAfter = new Range( pos, posEnd );
const fragBefore = editor.data.getSelectedContent( new Selection( [ rangeBefore ] ) );
const fragAfter = editor.data.getSelectedContent( new Selection( [ rangeAfter ] ) );
console.log( editor.data.stringify( fragBefore ) );
console.log( editor.data.stringify( fragAfter ) );
}