2012-07-10 55 views
1

我有一個小代碼來選擇CKEditor中的文本。爲此,我在javascript中使用以下代碼。在CKEditor getSelection()在IE中返回空值

 var docx = editor.document; 
     var elementx = docx.getById(id); 
     editor.getSelection().selectElement(elementx); 
     editor.getSelection().scrollIntoView(true); 

它正常工作,在Mozilla Firefox.But在IE9中,它拋出一個錯誤selectElement不是一個對象。所以我檢查了代碼,發現getSelection()有一個空值。請幫助我如何解決它。 我嘗試了一些在各種網站上給出的答案,即使在CKEditor中也沒有任何幫助。

回答

4

這是正確的解決方案:

var editor = CKEDITOR.instances.editor1; 
editor.focus(); // Without this selection will be null on IE. 

var element = editor.document.getBody().getLast(), 
    selection = editor.getSelection(); 

selection.selectElement(element); // You have to reuse selection. 
selection.scrollIntoView(); 

我測試了這個從Firefox,Chrome和IE8上的控制檯上運行http://ckeditor.com/demo,並且工作正常。

+0

感謝您的rply ..那'選擇'變量只有null。那getSelection()函數仍然只返回null .. – Ramesh 2012-07-16 09:52:00

+0

對不起,我無法重現那個。你能提供更多細節嗎? – Reinmar 2012-07-16 10:45:51

+0

只是我嘗試根據ID選擇特定的標籤。當我選擇它應該突出顯示,並滾動到這個位置,這是我想要的。 – Ramesh 2012-07-16 10:57:18

0

這可能工作。

var docx = editor.document; 
var elementx = docx.getById(id); 

var resRange = new CKEDITOR.dom.range(editor.document); 
resRange.selectNodeContents(elementx); 
resRange.collapse(); 
editor.getSelection().selectRanges([ resRange ]); 
resRange.endContainer.$.scrollIntoView(); 

這可能有事情做什麼IE9認爲是一個對象。你有沒有試過選擇不同的元素類型?

也許抓住元素的父會給你一些IE9認爲是一個對象,你可以試試這個:

var docx = editor.document; 
var elementx = docx.getById(id); 
var parentx = elementx.getParent(); 
parentx.scrollIntoView(); 
+0

非常感謝你花時間閱讀我所有的問題。我不知道爲什麼我總是得到錯誤的所有代碼.. U'r代碼還給出了一個selectRanges()不是一個對象錯誤。 – Ramesh 2012-07-16 09:54:53

+0

看看我的回答是否有幫助。 – codewaggle 2012-07-16 13:50:10