1. 阻止事件冒泡
使用 event.stopPropagation()
可以阻止事件冒泡。旧版本 IE 浏览器使用:event.cancelBubble = true
方法阻止事件冒泡。
兼容写法:
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
示例 :
<div class="box1">
<div class="box2">
<div class="box3"></div>
</div>
</div>
.box1{
width: 400px;
height: 400px;
background-color: blueviolet;
}
.box2{
width: 200px;
height: 200px;
background-color: yellow;
}
.box3{
width: 100px;
height: 100px;
background-color: pink;
}
// 获取元素
var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
var box3 = document.querySelector(".box3");
box1.addEventListener("click",function(){
console.log("box1");
})
box2.addEventListener("click",function(){
console.log("box2");
// 阻止冒泡
// event.stopPropagation();
})
box3.addEventListener("click",function(){
console.log("box3");
// 阻止冒泡
// event.stopPropagation();
})
2.阻止默认事件
使用 event.preventDefault()
可以阻止默认事件。旧版本 IE 浏览器使用:event.returnValue = false
阻止默认事件。
兼容写法:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
对于一般的默认事件,也可以通过设置事件处理函数 return false;
来达到阻止默认事件的目的。
<a href="http://doc.bufanui.com/">不凡学院</a>
<form>
<p>
性别: <input type="radio">男
<input type="radio">女
</p>
<p>
爱好: <input type="checkbox">看电影
<input type="checkbox">玩游戏
<input type="checkbox">写代码
</p>
</form>
// 获取元素
var link = document.querySelector("a");
var man = document.querySelectorAll("input[type='radio']")[0];
var movie = document.querySelectorAll("input[type='checkbox']")[0];
man.onclick = function(){
// 阻止默认点击事件
event.preventDefault();
}
movie.onclick = function(){
// 阻止默认点击事件
return false;
}
link.onclick = function(){
// 阻止链接跳转
return false;
}
文档更新时间: 2023-01-06 14:03 作者:孙老师