我试图使用纯Javascript (没有jQuery)循环遍历页面上的每个iframe,然后检查是否有任何iframe包含高亮显示(所选)文本。然后显示一个警报,显示突出显示的文本。杀手是..。iframes的ID不会提前被知道。因此,需要遍历每个iframe。FYI - iframes都在同一个域上,所以这里没有跨域问题.
我认为我的代码非常接近我所需要的,但到目前为止还没有雪茄。
在页面上,我要这样做.
var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].contentWindow.document.onmouseup = function() {
var iframeSelection = iframes[i].contentWindow.document.getSelection();
if (iframeSelection.toString().length > 0) { alert(iframeSelection); }
}
}还有..。对于这个特定的项目,它只需要在Chrome中工作。
谢谢!
发布于 2015-05-22 22:49:36
您的iframe和选择代码很好,但是在运行事件处理程序函数时,您将遇到一个具有for循环的for- i将始终等于iframes.length。
您可以通过使用Array.prototype.forEach进行迭代来避免这种情况。
var iframes = document.getElementsByTagName('iframe');
[].forEach.call(iframes, function(frame) {
frame.contentWindow.document.onmouseup = function() {
var iframeSelection = frame.contentWindow.getSelection();
if (iframeSelection.toString().length > 0) { alert(iframeSelection); }
}
});JSBin
https://stackoverflow.com/questions/30406846
复制相似问题