2019-01-09

javascript寫法 阻止事件冒泡
html代碼
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wrapper" class="wrapper">
<button id="clickMe">點我</button>
<div id="popover" class="popover">
浮層
<input type="checkbox">
</div>
</div>
</body>
</html>

css代碼

body{
border:1px solid red;
}
.wrapper{
position:relative;
display:inline-block;
}
.popover{
position:absolute;
top:0;
left:100%;
border:1px solid red;
white-space:nowrap;
padding:10px;
margin-left:10px;
display:none;
}
.popover::before{
position:absolute;
right:100%;
top:5px;
border:10px solid transparent;
border-right-color:purple;
content:'';
}
.popover::after{
position:absolute;
right:100%;
top:5px;
border:10px solid transparent;
border-right-color:white;
content:'';
}

clickMe.addEventListener('click',function(){
popover.style.display = 'block';
console.log('block');

});
wrapper.addEventListener('click',function(e){
e.stopPropagation();
});
document.addEventListener('click',function(){
popover.style.display="none";
console.log('none');
});

jQuery寫法
css 和html同上
(clickMe).on('click',function(){(popover).show();
});

//false等價于function(e)
{e.stopPropagation();
e.preventDefault();
}

$(wrapper).on('click',false);

當(dāng)回調(diào)函數(shù)是false的時候 如果div里有checkbox 那么將無法選擇 因為使用了阻止默認事件 怎么解決呢?那就阻止傳播 如下:
那就證明如果在checkbox的父元素或者checkbox上添加了阻止默認事件 那么這個CheckBox就沒辦法選擇
所以還是寫成$(wrapper).on('click',function(e) {
e.stopPropagation();
});

只監(jiān)聽一次 打掃戰(zhàn)場
(clickMe).on('click',function(){(popover).show();

(document).one('click',function(){(popover).hide();
console.log('document');
});
});
$(wrapper).on('click',function(e){
e.stopPropagation();
});

(clickMe).on('click',function(){(popover).show();
console.log('show');
setTimeout(function(){
console.log('添加click事件');
console.log('--------------');
$(document).one('click',function(){
console.log('我覺得不會執(zhí)行');
console.log('hide');

  $(popover).hide();
});

},0);
});

$(document).on('click',function(){
console.log('click走到了document');
});

①console.log("show");
②console.log("click執(zhí)行到了document");
③ console.log('添加click事件');
console.log('--------------');
④再點擊才會執(zhí)行console.log('我覺得不會執(zhí)行');
console.log('hide');

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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