我讀過這excellent answer幾乎相同的問題。然而,我已經嘗試了所有推薦的技術,並且它們都不起作用。CKEDITOR - 無法在DOM修改後恢復光標位置
這種情況是,我從編輯器中取出當前的HTML,並將範圍內的某些片段打包成標籤。然後,我將現在修改的HTML設置回來並嘗試恢復用戶的光標位置。沒有技術可行。
這是一個很簡單的例子來重現問題:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
</head>
<body>
<textarea id="cktest"><p>Sometimes Lorem. Sometime Ipsum. Always dolor.</p></textarea>
<script type="text/javascript">
(function() {
var checkTimeout;
var bookmark;
var storeCursorLocation = function(editor) {
bookmark = editor.getSelection().createBookmarks();
};
var restoreCursorLocation = function(editor) {
editor.getSelection().selectBookmarks(bookmark);
};
var validateText = function(editor) {
storeCursorLocation(editor);
var data = editor.document.getBody().getHtml();
data = data.replace("Lorem", "<span class='err-item'>Lorem</span>");
editor.document.getBody().setHtml(data);
restoreCursorLocation(editor);
};
CKEDITOR.replace('cktest', {
on: {
'instanceReady': function(evt) {
},
'key' : function(evt) {
clearTimeout(checkTimeout);
checkTimeout = setTimeout(function() {
validateText(evt.editor);
}, 1000);
}
}
});
})();
</script>
</body>
</html>
此代碼,當用戶按下一個鍵,然後等待1秒鐘後,他們停止按鍵做檢查啓動定時器。
將其複製到一個新的.html文件並在您喜歡的瀏覽器中運行(我正在使用Chrome)。
當CKEditor加載時,使用鼠標將光標置於文本中間的某個位置。然後按下CTRL鍵並等待1秒鐘。你會看到你的光標跳回到文本的開始處。
此代碼示例使用
editor.getSelection().createBookmarks();
創建書籤。但我也試過:
editor.getSelection().createBookmarks(true);
和
editor.getSelection().createBookmarks2();
我也嘗試過保存在restoreCursorLocation功能使用
var ranges = editor.getSelection().getRanges();
和
editor.getSelection().selectRanges(ranges);
的範圍內。
只需添加到此答案 - 一個更安全的解決方案將使用['CKEDITOR.style'](http://docs.ckeditor.com/#!/api/CKEDITOR.style),因爲它只會觸及必須更改的樹的這些部分。但是,要使用它,您需要實現一個在DOM中查找文本的函數,這是一件非常複雜的事情。 – Reinmar
感謝Reinmar的出色答案。在真實的代碼中,我使用CKEDITOR.htmlParser來瀏覽文檔並進行修改。不只是做一個簡單的.replace()。我會看看使用樣式,看看它是否更好。不知道爲什麼createBookmark(true)以前不適合我。但現在是。 –