我试图通过单击div外部来关闭我的div,但它也通过单击子元素隐藏自己
<div id="main-container">
<div id="profile-div">
<div id="user-pic"></div>
<span id="user-name">MANISH</span></div>
<ul>
<li><a href="#"><i class="fa fa-user-circle fa-2x"></i>Dahsbord</a></li>
<li><a href="#"><i class="fa fa-bell fa-2x"></i>Notification</a></li>
<li><a href="#"><i class="fa fa-comments fa-2x"></i>Contact us</a></li>
<li><a href="#"><i class="fa fa-wrench fa-2x"></i>Update Account</a></li>
<li><a href="#"><i class="fa fa-lock fa-2x"></i>Logout</a></li>
</ul>
</div>
window.addEventListener("mouseup", function (e) {
var div = document.getElementById("main-container");
if (e.target != div && e.target.parentNode != div) {
div.style.left = "-300px";
}
});
答案 0 :(得分:1)
ConnectionStrings
只给你元素的直接父元素,在这种情况下,如果可以是ul,li或内部div。相反,您可以使用parentNode
,它可以为您提供具有非静态位置的最近父级。
offsetParent
&#13;
window.addEventListener("mouseup",function(e){
var div = document.getElementById("main-container");
if(e.target != div && e.target.offsetParent != div){
div.style.left ="-300px";
}
});
&#13;
#main-container{
position: absolute;
border: 1px solid #000;
}
&#13;
答案 1 :(得分:0)
但不是log.innerHTML ='OUTSIDE';你把你的线隐藏了div
<style>
#main-container {
border: 1px solid red;
};
#profile-div {
border: 1px solid blue;
};
</style>
<div id="log"></div>
<div id="main-container">
<div id="profile-div">
<div id="user-pic"></div>
<span id="user-name">MANISH</span>
</div>
<ul>
<li><a href="#"><i class="fa fa-user-circle fa-2x"></i>Dahsbord</a></li>
<li><a href="#"><i class="fa fa-bell fa-2x"></i>Notification</a></li>
<li><a href="#"><i class="fa fa-comments fa-2x"></i>Contact us</a></li>
<li><a href="#"><i class="fa fa-wrench fa-2x"></i>Update Account</a></li>
<li><a href="#"><i class="fa fa-lock fa-2x"></i>Logout</a></li>
</ul>
</div>
</div>
<script>
window.onload = function(e) {
var div = document.getElementById("main-container");
var id = "main-container";
var log = document.getElementById("log");
window.addEventListener("mouseup", function(e) {
if( checkParents(e.target, id)) {
log.innerHTML = 'INSIDE';
}
else {
log.innerHTML = 'OUTSIDE';
}
},
false);
function checkParents(elm, id) {
var parent = elm;
do {
if(parent.id == id) {
return true;
}
if(parent == window) {
return false;
}
} while(parent = parent.parentNode) ;
}
}
</script>