iframe中选定的文字

时间:2009-11-13 04:26:51

标签: javascript jquery

如何在iframe中获取所选文字。

我的页面我有一个可编辑的iframe。 那么如何在iframe中获取所选文本。

3 个答案:

答案 0 :(得分:2)

忽略我写的内容,这是垃圾。

这是真正的交易:

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

上述内容从bobince's回复this SO Question

后被公然偷走

答案 1 :(得分:0)

我不确定所选文本的确切含义,但这是您使用jquery访问iframe内容的方式

$('#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;
    }
} 

答案 2 :(得分:0)

不确定iframe的editable true是什么意思。可能是文本字段或文本区域。但是如果你真的有一个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;
}
相关问题