话不多说,上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
padding:0;
margin:0;
}
li{
width:50px;
height:20px;
border:1px solid red;
background-color: antiquewhite;
text-align: center;
list-style: none;
cursor: pointer;
}
.preDefault{
background-color: yellow;
width:500px;
height:500px;
margin:auto;
}
</style>
</head>
<body>
<div onclick="alert('点击了div')">
<ul onclick="alert('点击了ul')">
<li>
test
</li>
</ul>
</div>
<div class="preDefault">
</div>
</body>
<script>
// 阻止事件冒泡
const li = document.querySelector("li")
li.onclick = function(e){
if(e.stopPropagation){
e.stopPropagation()
}else{
window.event.cancel = true//兼容IE6、7、8
}
alert("点击了li")
}
// 阻止默认事件
const preDefault = document.querySelector(".preDefault")
preDefault.oncontextmenu =function(e){//鼠标右键点击
if(e.preventDefault){
e.preventDefault()
}else{
window.event.returnValue = false //兼容IE6、7、8
}
alert("阻止了默认事件")
}
</script>
</html>
阻止事件冒泡:
e.stopPropagation() //w3c写法
window.event.cancel = true //低版本ie写法
//兼容写法如下:
if(e.stopPropagation){
e.stopPropagation()
}else{
window.event.cancel = true//兼容IE6、7、8
}
阻止默认事件(比如:右键点击事件)
e.preventDafault()//w3c写法
window.event.returnValue = false //兼容低版本ie
//兼容性写法如下:
if(e.preventDefault){
e.preventDefault()
}else{
window.event.returnValue = false //兼容IE6、7、8
}
如果对您有一丝的帮助,请赏个赞可好~