我知道 <a href="http://www.example.com" target="_blank">Click here</a>
在新选项卡中 打开链接(Chrome 和 Firefox 中的默认行为)并且
<a href="http://www.example.com" onclick="window.open('http://www.example.com',
'newwindow', 'width=700,height=500'); return false;">Click here</a>
在新窗口中 打开它。
但是 如何在模式弹出窗口中打开外部页面(以屏幕为中心,原始页面的其余部分“变暗”)?
有什么好的方法吗?
我尝试了以下代码,但它似乎不起作用(单击:弹出窗口打开,重新单击,它关闭,重新单击链接:它不再打开。iframe 也没有加载)。
document.getElementById("a").onclick = function(e) {
e.preventDefault();
document.getElementById("popup").style.display = "block";
document.getElementById('iframe').src = "http://example.com";
document.getElementById('page').className = "darken";
setTimeout(function() {
document.getElementById('page').onclick = function() {
document.getElementById("popup").style.display = "none";
document.getElementById('page').className = "";
}
}, 100);
return false;
}
#popup {
display: none;
border: 1px black solid;
width: 400px; height: 200px;
top:20px; left:20px;
background-color: white;
z-index: 10;
padding: 2em;
position: fixed;
}
.darken { background: rgba(0, 0, 0, 0.7); }
#iframe { border: 0; }
html, body, #page { height: 100%; }
<div id="page">
<a href="" id="a">Click me</a><br>
Hello<br>
Hello<br>
<div id="popup">
External website:
<iframe id="iframe"></iframe>
</div>
</div>
原文由 Basj 发布,翻译遵循 CC BY-SA 4.0 许可协议
根本原因是
page.onclick is registered after popup window is open at the first time, then the following 'open popup' will trigger a.onclick and page.onclick in a row, that caused the popup window is open then is closed directly
。简单的解决方案是添加一个参数来控制弹出窗口的状态。如果弹出窗口关闭,则在 page.onclick 中不执行任何操作。
要删除 setTimeout,有两种解决方案:
添加了另一个参数来控制弹出初始化的状态。
Don’t make
<div id="page">
is the parent of<a id="popup">
, so<a id="popup">
will not be triggered when clicked<div id="page">
.以下是两种解决方案:
解决方案 1 :如果弹出窗口已完成初始化,则添加
isInit
作为指示符。PS :在评论中,您提到只有在单击
<div id="page">
时才关闭弹出窗口,要在解决方案 1 中实现这一点,我认为您必须绑定事件 =mouseout
,mouseenter
判断鼠标点击的位置。解决方案 2 :使
<div id="page">
和<a id="popup">
是堂兄而不是父母关系。