我想在单击 iframe 窗口中的任意位置时打开新选项卡。
<div id="iframeDiv">
<iframe id="frame" src="anysite.com" width="100%" height="400"></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)
单击 iframeDiv 时,我想在新的浏览器选项卡中打开 anysite.com
浏览器将 视为iframe另一个页面,不会向父页面抛出事件。这意味着实际检测对 的点击的唯一方法iframe是将一个不可见的元素放在 的前面iframe,这样您实际上并不是在框架上单击,而是在覆盖的元素上单击。
var iframeContainers = document.getElementsByClassName("iframe-container");
for (let container of iframeContainers) {
container.addEventListener("click", function(event) {
let iframe = event.target.parentElement.querySelector('iframe');
if (iframe) {
let url = iframe.getAttribute('src');
window.open(url, '_blank').focus();
}
});
}Run Code Online (Sandbox Code Playgroud)
.iframe-container {
position: relative;
background-color: yellow;
height: 300px;
width: 300px;
}
.iframe-container > iframe {
width: 100%;
height: 100%;
}
.iframe-container > .iframe-overlay {
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}Run Code Online (Sandbox Code Playgroud)
<div class="iframe-container">
<iframe id="iframe" src="https://www.example.com"></iframe>
<div class="iframe-overlay"></div>
</div>Run Code Online (Sandbox Code Playgroud)
由于某种原因,代码片段的点击行为在 Stack Overflow 环境中不起作用,但它在 jsFiddle 上起作用:
https://jsfiddle.net/nathanwailes/xtzqy35u/40/
| 归档时间: |
|
| 查看次数: |
10535 次 |
| 最近记录: |