我正在开发自动填充插件,我的要求是在按下空格键的同时选择光标之前的单词,这样我就可以获得选定的文本并填充或插入新文本。
例如,在“ck”后按空格时,我将“ck”替换为“CKEditor”。
我所做的是,在按空格键时,我将光标之前的单词作为键,如果键是“ck”,我通过选择带有范围的“ck”并插入新单词“CKEditor”将其替换为“CKEditor”
if (e.data.keyCode == 32) {
var s = editor.getSelection();
var cursor = s._.cache.nativeSel.anchorOffset;
var data = s._.cache.nativeSel.focusNode.data;
var node = s._.cache.nativeSel.focusNode;
var selection = editor.getSelection();
data = data.substring(0,cursor)
var startIndex = data.lastIndexOf(" ");
if (startIndex==-1) {
startIndex=0;
} else {
startIndex=startIndex+1;
}
var key = data.substring(startIndex,data.length);
// HERE KEY IS THE WORD BEFORE CURSOR, THERE IS NO ISSUE IN IT.
key = key.trim();
if (key.trim() == 'ck') {
var ranges = [];
var range, text, index;
console.log(editor.getSelection().getStartElement());
var text = getTextNodes( editor.getSelection().getStartElement() ,key );
range = editor.createRange();
range.setStart( text, cursor - (key.length));
range.setEnd( text, cursor);
ranges.push( range );
selection.selectRanges( ranges );
editor.insertHtml('CKEditor');
}
// GETTING NODE OF THE KEY
function getTextNodes( element,key ) {
var children = element.getChildren();
var 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 ) {
if (child.$.data.indexOf(key)!=-1) {
var text = child;
return child;
}
}
}
它工作正常 99%,但如果“ck”是新行的第一个单词,它会失败。