2009-12-09 42 views

回答

2

沒有爲IE中的文檔對象沒有getSelection方法的答案,您必須改用選擇對象。

var selText; 
var iframeWindow = document.getElementById('iView').contentWindow; 
if (iframeWindow.getSelection) 
    selText = iframeWindow.getSelection()+""; 
else if (iframeWindow.document.selection) 
    selText = iframeWindow.document.selection.createRange().text; 
+0

爲什麼需要檢查iframeWindow.getSelection或iframeWindow.document.selection? – samuel 2009-12-09 22:43:16

+0

您正在檢查存在的功能,這實質上是瀏覽器檢查。如果瀏覽器不支持該方法,那麼這些語句將返回false並且腳本不會執行 - 如果檢查不存在,並且瀏覽器不支持該方法,則會拋出錯誤。或者,您可以使用try/catch語句,但這通常是功能測試的實際方法。 – 2009-12-09 22:54:30

+1

@samuel:這是一個非常好的答案,但幾乎與您提到的其他問題中發現的一對夫婦相同(http://stackoverflow.com/questions/1471759/how-to-get-selected-text-from-iframe -with-javascript),那麼這又給了你新的信息呢? – 2009-12-10 10:40:53