从javascript中选择CKEditor中的文本范围

时间:2013-06-25 10:12:13

标签: ckeditor

我想在CKEditor中选择一个特定的文本。我使用了以下内容:

var sel = editor.getSelection();

var element = sel.root;
console.log(element);
sel.selectElement(element);
var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);

if (startIndex != -1) {
    ranges[0].setStart(element.getFirst(), startIndex);
    console.log(element.getFirst() +" - "+ startIndex);
    console.log(element.getFirst() +" - "+ startIndex + findString.length);
    ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
    sel.selectRanges([ranges[0]]);
}

如果它是没有换行符的纯文本,它可以正常工作。 如果我想要选择的文本是在第二行之后或者是格式化的,我会收到以下错误:

  

未捕获错误:IndexSizeError:DOM异常1

出了什么问题?

1 个答案:

答案 0 :(得分:4)

我重新访问了您的代码并“稍微改变了一下”。以下代码将在编辑器内容中选择“the”一词的所有出现次数

// Note: your instance name may differ.
var editor = CKEDITOR.instances.editor1, 
    selection = editor.getSelection(),
    root = selection.root,
    textNodes = [],
    ranges = [],
    range, text, index;

function getTextNodes( element ) {
    var children = element.getChildren(),
        child;

    for ( var i = children.count(); i--; ) {
        child = children.getItem( i );
        if ( child.type == CKEDITOR.NODE_ELEMENT ) 
            getTextNodes( child );
        else if ( child.type == CKEDITOR.NODE_TEXT )
            textNodes.push( child );
    }
}

// Recursively search for text nodes starting from root.
// You may want to search a specific branch starting from other element.
getTextNodes( root ); 

// Iterate over found text nodes. If some contains
// phrase "the", create a range that selects this word.
for ( i = textNodes.length; i--; ) {
   text = textNodes[ i ];
   index = text.getText().indexOf( 'the' );
   if ( index > -1 ) {
      range = editor.createRange();
      range.setStart( text, index );
      // Note: 3 is fixed length of "the". You may want to change it.
      range.setEnd( text, index + 3 ); 
      ranges.push( range );
   }  
}

// Select all ranges "containing" phrase "the".
selection.selectRanges( ranges );

请注意,如果您在Chrome或IE中运行此代码,则只会选择第一次出现。 只有Firefox支持多项选择,结果应如下所示:

Multiple selections in Firefox

我希望这个例子可以帮助你解决问题。

相关问题
最新问题