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); //點(diǎn)擊xiao或者jian 出現(xiàn)1
})
_con.has(event.target).length的作用:用來(lái)判斷點(diǎn)擊的位置是否在目標(biāo)區(qū)域的子元素上,也就是事件對(duì)象是不是目標(biāo)區(qū)域的子元素,長(zhǎng)用在點(diǎn)擊彈窗區(qū)域外彈窗消失的代碼中。
_con.is(e.target)用來(lái)判斷點(diǎn)擊位置是否在目標(biāo)區(qū)域內(nèi),如果不在,則返回false;否則true

0a1a77a7850f358c2e87f45d9be892d.png

點(diǎn)擊彈窗消失的代碼例子:
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">點(diǎn)擊</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');   // 設(shè)置目標(biāo)區(qū)域
                if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
                    $('.pop').hide();   // 功能代碼
                    $('.gray').hide()
                }
               
            });
                /* Mark 1 的原理:
                判斷點(diǎn)擊事件發(fā)生在區(qū)域外的條件是:
                1. 點(diǎn)擊事件的對(duì)象不是目標(biāo)區(qū)域本身
                2. 事件對(duì)象同時(shí)也不是目標(biāo)區(qū)域的子元素
                */  
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容