问题描述
< div id =iframeDiv> 我想在iframe窗口中的任何位置点击打开新标签。 ;
< iframe id =framesrc =anysite.comwidth =100%height =400>< / iframe>
< / div>
点击iframeDiv,我想在新浏览器标签中打开anysite.com
您可能会尝试的是在元素上添加一个侦听器:
var iframeDiv = document.getElementById(iframeDiv);
iframeDiv.addEventListener(click,function(e){
window.location.href = document.getElementById(frame)。src;
},true) ;
true
addEventListener
调用告诉浏览器在捕获时运行此函数,这意味着在iframe内部执行事件之前。如果你不这样做,在JavaScript事件运行之前单击iframe内的链接将会跟随该链接。可悲的是,捕获事件与IE不兼容
但它不适用于iframe!
$ b
我认为这可以起作用,但似乎浏览器将iframe视为其他页面,并且不会将事件扔到父项上。这意味着实际检测对iframe点击的唯一方法是在iframe前放置一个不可见的元素,以便实际上不是在框架上单击,而是在元素上单击。
#iframeDiv {position:absolute; background-color:yellow;}#frameDummy {position:absolute; top:0px; bottom:0px; left:0px; right:0px;}
< div id =iframeDiv > < iframe id =framesrc =/width =200height =200>< / iframe> < div id =frameDummy>< / div>< / div>
I want to open new tab on clicking of anywhere in iframe window.
<div id="iframeDiv">
<iframe id="frame" src="anysite.com" width="100%" height="400"></iframe>
</div>
on click of iframeDiv , I want to open anysite.com in new browser tab
What you might try is to add a listener on the element:
var iframeDiv = document.getElementById("iframeDiv");
iframeDiv.addEventListener("click", function(e) {
window.location.href = document.getElementById("frame").src;
}, true);
The true
passed after the function in the addEventListener
call tells the browser to run this function on capture, which means before the event is executed inside the iframe. If you don't do that, clicking on a link inside the iframe would follow that link before the JavaScript event runs. Sadly, capture events aren't compatible with IE<9
But it doesnt work with iframes!
I thought this could work, but it seems browsers treat the iframe as an other page and will not throw events on the parent. This means that the only way to actually detect clicks on an iframe is to put an invisible element in front of the iframe so that you're not actually clicking on the frame, but on the element.
var iframeDiv = document.getElementById("iframeDiv");
iframeDiv.addEventListener("click", function(e) {
window.location.href = document.getElementById("frame").src;
});
#iframeDiv {
position: absolute;
background-color: yellow;
}
#frameDummy {
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
<div id="iframeDiv">
<iframe id="frame" src="/" width="200" height="200"></iframe>
<div id="frameDummy"></div>
</div>
这篇关于点击iframe,在浏览器中打开新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!