我正在尝试找到一种可靠的方法来在编辑器中输入某些文本时执行回调。我想在键入@时运行某些代码(然后允许选择用户链接)。
目前我正在使用“更改”事件,然后尝试回顾当前选择之前的内容:
CKEDITOR.plugins.add( 'ipsmentions', {
init: function( editor ) {
/* When the content of the editor is changed, check if it was an @ */
editor.on( 'change', function(e) {
/* If we currently have just normal text selected, we're typing normally and there might be an @ */
var selection = editor.getSelection();
if ( selection.getType() == CKEDITOR.SELECTION_TEXT ) {
/* Loop the ranges... */
var ranges = selection.getRanges( true );
for ( var i = 0; i < ranges.length; i++ ) {
/* If the start container and end container are the same (meaning we just have a normal caret, indicating normal typing, nothing highlighted) and that is a text node... */
if ( ranges[i].startContainer.equals( ranges[i].endContainer ) && ranges[i].endContainer instanceof CKEDITOR.dom.text ) {
if ( ranges[i].startContainer.getText().substr( ranges[i].startOffset - 1, 1 ) == '@' ) {
console.log('@ pressed!');
}
}
}
}
});
}
});
但我猜这不是最好的方法。特别是,我注意到如果我键入@然后按回车键(开始一个新段落),我再次在控制台中“@press”。
有没有更好的方法来解决这个问题?
答案 0 :(得分:0)
异步检查应该有助于输入密钥。我也会使用一些向后range.cloneContents
,因为你永远不知道选择可能锚定在哪种类型的节点上。 JSFiddle
CKEDITOR.replace( 'editor', {
on: {
change: function() {
CKEDITOR.tools.setTimeout( function() {
var sel = this.getSelection(),
range = sel.getRanges()[ 0 ];
if ( !range.collapsed ) {
console.warn( 'non–collapsed range' );
return;
}
if ( !range.startOffset ) {
console.warn( 'at the beginning of the node' );
return;
}
range.setStart( range.startContainer, 0 );
if ( range.cloneContents().$.textContent.substr( -1 ) == '@' ) {
console.log( '@ inserted' );
}
}, 0, this );
}
}
} );