当用户在该帧中选择文本时,确定帧ID /名称 - 该页面具有多个帧 [英] determine the frame id/name when a user has selected text in that frame- the page has multiple frames
问题描述
我有一个场景,其中在一个网页中打开了多个iframe /帧。现在,用户可以在任何一个打开的框架/ iframe中选择一些文本。我想确定用户选择文本的iframe的ID /名称,使用iframe id / name我将对所选文本执行一些操作。
I have a scenario in which there are multiple iframes/frames open in one web page. Now user may select some text in any one of the open frames/iframes. I want to determine the id/name of the iframe in which user has selected text, using the iframe id/name I will then do some operations on the selected text.
我该怎么做呢?
推荐答案
这将获得具有非空选择的curent文档中的第一个iframe。如果iframe来自另一个域,因此无法访问当前文档中运行的JavaScript,则无法检索选择并忽略iframe。
This will get the first iframe in the curent document that has a non-empty selection. If an iframe is from another domain and hence inaccessible to JavaScript running in the current document, the selection cannot be retrieved and the iframe is ignored.
function getSelectedText(win) {
var sel;
if (win.getSelection) {
return "" + win.getSelection();
} else if ( (sel = win.document.selection) ) {
if (sel.type == "Text") {
return sel.createRange().text;
}
}
return "";
}
function getIframeWithSelection(win) {
var iframes = win.document.getElementsByTagName("iframe");
for (var i = 0, len = iframes.length, selectedText; i < len; ++i) {
try {
selectedText = getSelectedText(iframes[i].contentWindow);
if (selectedText != "") {
// alert just there for debugging
alert(selectedText);
return iframes[i];
}
} catch (e) {}
}
return null;
}
// Example
var iframe = getIframeWithSelection(window);
这篇关于当用户在该帧中选择文本时,确定帧ID /名称 - 该页面具有多个帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!