2009-11-13 62 views
-1

如何获取iframe中的选定文本。iframe中的选定文本

我的页面我有一个可编辑的iframe iframe。 那么我怎样才能得到该iframe中的选定文本。

+1

这是http://stackoverflow.com/questions的精确副本/ 1471759/how-to-get-selected-text-from-iframe-with-javascript – 2009-11-13 04:45:15

+0

@Dan McG - 然后投票! – 2009-11-13 04:51:47

+0

-1。我知道我忘了一些东西... – 2009-11-13 05:16:21

回答

0

林不知道究竟你被选中的文字是什么意思,但是这是你如何访问一个iframe的内容与jQuery

$('#iFrameID').contents().find('#whatImLookingFor').text(getSelectedText()); 

function getSelectedText(){ 
    if(window.getSelection){ 
     return window.getSelection().toString(); 
    } 
    else if(document.getSelection){ 
     return document.getSelection(); 
    } 
    else if(document.selection){ 
     return document.selection.createRange().text; 
    } 
} 
+0

选择文本的意义(使用鼠标选定的文本) – Santhosh 2009-11-13 04:40:58

2

忽略了什么我已经写了,那是垃圾。

这是实打实的:

var iframe= document.getElementById('yourFrameId'); 
var idoc= iframe.contentDocument || iframe.contentWindow.document; // For IE. 
alert(idoc.getSelection()); 

以上是公然从bobince's答案被盗this SO Question

0

不知道你在iframe的意思编辑真实的东西。可能是文本框或者textarea。但是,如果你真的有一个iframe,在一些文本被选中,那么这里是一个代码段,应该在一些浏览器的工作:

var iframe = document.getElementById("frame1"); 
var txt = ""; 
if (iframe.contentWindow.getSelection) { 
    txt = iframe.contentWindow.getSelection(); 
} else if (iframe.contentWindow.document.getSelection) { 
    txt = iframe.contentWindow.document.getSelection(); 
} else if (iframe.contentWindow.document.selection) { 
    txt = iframe.contentWindow.document.selection.createRange().text; 
}