单击外部div以隐藏纯JavaScript中的div [英] Click outside div to hide div in pure JavaScript
本文介绍了单击外部div以隐藏纯JavaScript中的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想制作一个弹出窗口,一旦点击一个按钮就会出现,一旦用户点击框外,就会消失。
I want to make a popup that should appear once a button is clicked and disappear once the user clicks outside of the box.
我不知道怎么做当我在它外面点击时,让div消失。
I'm not sure how to make the div disappear when I click outside of it.
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">
这是第一个版本......
这是一些代码。如果还有其他要添加的内容,请告诉我们:)
Here is some code. If there is anything else to add, please let me know :)
事件(e)对象可以访问有关该事件的信息。 e.target为您提供触发事件的元素。
The event (e) object gives access to information about the event. e.target gives you the element that triggered the event.
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>
这篇关于单击外部div以隐藏纯JavaScript中的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文