has()

<div class="pop" style="width: 200px;height: 200px;background: pink;display: block;z-index: 333;position: absolute;">
显示<div>xiao</div><small>jian</small>
</div>

$('.pop').click(function(){
var _con = $('.pop');
alert(_con.has(event.target).length); //点击xiao或者jian 出现1
})
_con.has(event.target).length的作用:用来判断点击的位置是否在目标区域的子元素上,也就是事件对象是不是目标区域的子元素,长用在点击弹窗区域外弹窗消失的代码中。
_con.is(e.target)用来判断点击位置是否在目标区域内,如果不在,则返回false;否则true

0a1a77a7850f358c2e87f45d9be892d.png

点击弹窗消失的代码例子:
html代码:
<div class="pop" style="width: 200px;height: 200px;background: pink;display: block;z-index: 333;position: absolute;">
显示<div>xiao</div><small>jian</small>
</div>
<div class="clic">点击</div>
<div class="gray" style="z-index: 222;background: gray;top: 0rem;bottom: 0px;position: absolute;width: 100%;display: none;">遮罩层</div>
js代码:
$('.clic').click(function(){
$('.pop').show();
$('.gray').show();
})

            $('.gray').click(function(e){
                console.log(event.target);
                var _con = $('.pop');   // 设置目标区域
                if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
                    $('.pop').hide();   // 功能代码
                    $('.gray').hide()
                }
               
            });
                /* Mark 1 的原理:
                判断点击事件发生在区域外的条件是:
                1. 点击事件的对象不是目标区域本身
                2. 事件对象同时也不是目标区域的子元素
                */  
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容