如何使用 javascript 从 iframe 中获取选定的文本?
问问题
4972 次
2 回答
2
var $ifx = $('<iframe src="filename.html" height=200 width=200></iframe>').appendTo(document.body);
$(document.body).bind('click', function(){
var u_sel;
if(window.getSelection){
u_sel = ifx[0].contentWindow.getSelection();
// u_sel.text() InternetExplorer !!
alert(u_sel);
}
});
应该这样做,只要iframe src
是针对您自己的domain
. FireFox 3.6.7
到目前为止只测试过。
于 2010-07-24T12:01:05.260 回答
0
function getIframeSelectionText(iframe) {
var win = iframe.contentWindow;
var doc = iframe.contentDocument || win.document;
if (win.getSelection) {
return win.getSelection().toString();
} else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange().text;
}
}
var iframe = document.getElementById("your_iframe");
alert(getIframeSelectionText(iframe));
正如 jAndy 所指出的,这仅在 iframe 文档与包含文档来自同一域时才有效。
于 2010-07-24T20:12:58.183 回答