[英]Move caret to the end of a word in a tinyMCE editor
我正在嘗試為我的tinyMCE編輯器構建一個函數,該函數會在您鍵入時用span標簽包裹某些單詞,到目前為止,在初始化tinyMCE實例時,我已經在init_instance_callback
選項中使用了該函數:
function(ed) {
ed.on('keyup', function () {
var editor = tinyMCE.get('content'),
regex = new RegExp('test|abc', 'gi'),
oldContent = editor.getContent(),
newContent = oldContent.replace(regex, '<span style="background-color: yellow;">$&</span>');
// Save cursor position
var marker = editor.selection.getBookmark(2);
// Set new content in editor
editor.setContent(newContent);
// Move cursor to where it was
editor.selection.moveToBookmark(marker);
});
}
這是一個帶有工作示例的小提琴: http : //fiddle.tinymce.com/Jjeaab
在您鍵入內容時,它可以正常工作,但是只要您輸入匹配的單詞之一(在本例中為“ test”或“ abc”),然后插入符號就會移至單詞的開頭,我相信這是因為在span元素中添加額外的字符,以便在單詞被換行后不能正確設置書簽,有沒有辦法解決此問題?
也許您可以插入一個新的Node而不是替換所有內容。 它將為您管理定位。
在此之前,您也只是刪除了匹配的字符串(我讓您檢查如何正確執行此操作)。
這是一個例子:
ed.on('keyup', function () {
var editor = tinyMCE.get('content'),
regex = new RegExp('test|abc', 'i');
var match = editor.getContent().match(regex);
if (match) {
// Here remove the "match[1].length" last character
// Then add the new Node, it will set the cursor just after it
editor.selection.setNode(editor.dom.create('span', {style : 'background-color: yellow;'}, match[1]));
}
});
您可能還必須查看RegExp以防止與您創建的節點匹配(您只希望匹配用戶鍵入的字符串->不由span標簽包圍)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.