本文摘自PHP中文网,作者逆旅行人,侵删。
在Javascript
中事件冒泡是由节点产生,然后会影响到父节点,逐级上升,最后慢慢影响到整个页面,但是有时我们想要阻止事件冒泡的发生甚至事件本身的发生呢?本文就带大家一起来了解一下。1.阻止事件冒泡发生
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >Document</ title >
< style >
.boxA {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: blue;
text-align: center;
}
.boxB {
width: 200px;
height: 200px;
margin: 50px;
background-color: green;
line-height: 200px;
color: #fff;
}
</ style >
</ head >
< body >
< div class = "boxA" >
< div class = "boxB" >boxB</ div >
</ div >
< script >
var boxA = document.querySelector('.boxA');
var boxB = document.querySelector('.boxB');
boxA.onclick = function (e) {
console.log('我被点击了boxA');
};
boxB.onclick = function (e) {
e.cancelBubble=true; //不冒泡
console.log('我被点击了boxB');
};
</ script >
</ body >
</ html >
|
2.阻止事件本身发生
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >Document</ title >
</ head >
< form action = "http://www.php.cn" method = "POST" >
< button type = "submit" >按钮1</ button >
</ form >
< body >
< script >
const btn=document.querySelector("button");
console.log(btn);
btn.addEventListener("click",function(e){
e.preventDefault();
});
</ script >
</ body >
</ html >
|
推荐:《2021年js面试题及答案(大汇总)》
以上就是Javascript如何阻止事件冒泡和事件本身发生的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
js绘制两个相交的矩形并且其中有一个包含透明度
javascript怎么设置div边框
javascript some()方法怎么用
原来es6 module还可以这样用!(备忘单)
介绍js的四种类型检测方法及根据jquery写的工具方法
javascript push()方法有什么用
浏览器的事件循环详解
javascript如何实现鼠标左键拖拽效果
vue keep-alive组件的使用以及原理介绍
深入了解js中的for...of循环
更多相关阅读请进入《事件冒泡》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » Javascript如何阻止事件冒泡和事件本身发生