js点击任意区域弹出层消失实现代码
本文实例为大家分享了js点击任意区域弹出层消失的具体代码,供大家参考,具体内容如下
采用jqueryelement.parents();判断点击区域是否在弹出层上面或者在按钮上面,否则让弹出层消失。
完整代码
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
</head>
<body>
<pre>
parent>child
在给定的父元素下匹配所有的子元素
</pre>
<divclass="help">
<spanclass="bnt">我是弹出层</span>
<ulid="list"class="foo">
<li><ahref="#">第1条记录</a></li>
<li><ahref="#">第2条记录</a></li>
<li><ahref="#">第3条记录</a></li>
<li><ahref="#">第4条记录</a></li>
</ul>
</div>
<style>
.bnt{
width:100px;height:50px;background:#777;color:#fff;
display:block;
text-align:center;
line-height:50px;
cursor:default;
}
.helpul{
display:none;
border:1pxsolid#aaa;
}
a{display:block;padding:10px;}
</style>
<scriptsrc="../jquery.js"></script>
<script>
(function($){
$('.bnt').click(function(){
if($(this).hasClass('show')){
$('.helpul').hide();
$(this).removeClass('show')
return;
}
$('.helpul').show();
$(this).addClass('show')
})
document.addEventListener('click',function(e){
varparent=$(e.target).parents('.foo,.help');
if(parent.length===0){
console.log('不在弹层与按钮区')
//操作此区域
$('.helpul').hide();
$('.bnt').removeClass('show');
}else{
console.log('按钮与弹层区')
}
})
})(jQuery);
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。