我想制作一个弹出窗口,一旦点击一个按钮就会出现,一旦用户点击该框,就会消失.
当我在它外面点击时,我不确定如何让div消失.
var popBox = document.getElementById("popBox"); document.getElementById("linkBox").onclick = function () { popBox.style.display = "block"; }; ???.onclick = function () { popBox.style.display = "none"; };
解决方法
这是第二个版本,它有一个透明的叠加层,如评论员在评论中提出的那样…
window.onload = function(){ var popup = document.getElementById('popup'); var overlay = document.getElementById('backgroundOverlay'); var openButton = document.getElementById('openOverlay'); document.onclick = function(e){ if(e.target.id == 'backgroundOverlay'){ popup.style.display = 'none'; overlay.style.display = 'none'; } if(e.target === openButton){ popup.style.display = 'block'; overlay.style.display = 'block'; } }; };
#backgroundOverlay{ background-color:transparent; position:fixed; top:0; left:0; right:0; bottom:0; display:block; } #popup{ background-color:#fff; border:1px solid #000; width:80vw; height:80vh; position:absolute; margin-left:10vw; margin-right:10vw; margin-top:10vh; margin-bottom:10vh; z-index:500; }
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div> <div id="backgroundOverlay"></div> <input type="button" id="openOverlay" value="open popup">
这是第一个版本……
事件(e)对象提供对事件信息的访问. e.target为您提供触发事件的元素.
window.onload = function(){ var divToHide = document.getElementById('divToHide'); document.onclick = function(e){ if(e.target.id !== 'divToHide'){ //element clicked wasn't the div; hide the div divToHide.style.display = 'none'; } }; };
<div id="divToHide">Click outside of this div to hide it.</div>