2

CKEditor5 Balloon Editor在 Angular2+ 中,当我在实例内单击时,我试图获取插入符号的确切位置。我将在页面上有几个实例,每个实例都通过 a@ViewChildren和 a动态表示QueryList(每个实例都是一个单独的编辑器)。

在高层次上,我试图在用户单击气球编辑器时触发一个方法,它将光标之前的所有文本存储在一个变量中,然后将光标之后的所有文本存储在另一个变量中。

即,如果用户Hello world this is a test在“world”之后的 div 内键入并单击,它将“Hello world”存储在一个变量中,“this is a test”存储在另一个变量中。

关于如何做到这一点的任何想法?我假设我需要创建两个实例,Position然后以某种方式将其输入 a Range,但我不知道如何Position输入正确的路径。

如果有人对 CKEditor 5 的常规旧单个实例有工作方法,我将不胜感激。谢谢!

4

1 回答 1

1

完整的解决方案将如下所示:

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 ) );
}
于 2017-12-14T12:18:13.533 回答