2019-01-09

javascript写法 阻止事件冒泡
html代码
<!DOCTYPE html>
<html>
<head>
<script src="//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);

当回调函数是false的时候 如果div里有checkbox 那么将无法选择 因为使用了阻止默认事件 怎么解决呢?那就阻止传播 如下:
那就证明如果在checkbox的父元素或者checkbox上添加了阻止默认事件 那么这个CheckBox就没办法选择
所以还是写成$(wrapper).on('click',function(e) {
e.stopPropagation();
});

只监听一次 打扫战场
(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('我觉得不会执行');
console.log('hide');

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

},0);
});

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

①console.log("show");
②console.log("click执行到了document");
③ console.log('添加click事件');
console.log('--------------');
④再点击才会执行console.log('我觉得不会执行');
console.log('hide');

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容