什么是事件冒泡?
事件冒泡就是从内向外扩散触发。
例如: <p>在<div>里面,<p>有一个onclick事件,<div>也有一个onclick事件,
这时点击<p>,<p>onclick事件和<div>的onclick都会触发.
<style>
.father {
text-align: center;
width: 200px;
height: 200px;
background-color: rgb(8, 120, 224);
}
.son {
margin: 30px auto;
width: 100px;
height: 100px;
background-color: rgb(20, 248, 134);
}
</style>
</head>
<body>
<div class="father">
我是父元素
<p class="son">我是子元素</p>
</div>
<script>
var father = document.querySelector('.father') //获取father元素
var son = document.querySelector('.son') //获取son元素
father.onclick = function () { //给father注册点击事件
console.log('father触发') //事件触发时打印father触发了
}
son.onclick = function (e) { //给son注册点击事件
console.log('son触发') //事件触发时打印son触发了
}
</script>
</body>
点击son时,结果是:son和father都会触发。这就是事件冒泡
阻止事件冒泡
给son添加,stopPropagation()
son.onclick = function () {
console.log('son触发l')
event.stopPropagation() //关闭事件冒泡
}
事件捕获
事件捕获是由外向内触发,与事件冒泡想反。
开启事件捕获,addEventListener(‘事件’,function(){},true).
addEventListenerd()第三个参数为true表示开启事件捕获
father.addEventListener('click',function(){
console.log('father触发了')
},true)
son.addEventListener('click',function(){
console.log('son触发了')
},true)
点击son时执行结果为,先打印:father触发了 ,在打印:son触发了。
阻止默认行为
js中有些元素具有默认行为,例如点击a标签跳转,在页面中右键鼠标弹出的菜单,form表单中点提交按钮submint,页面会产生一个提交行为并刷新网页等。
使用event.preventDefault()阻止默认行为。
(ie9以下)用event.returnValue=false;
例1:阻止“a”标签的默认跳转行为
存在“a”标签的点击事件中
<a href="http://www.baidu.com">百度</a>
<script>
var btn=document.querySelector('a');
btn.onclick=function(){
if(event.preventDefault()){ //有preventDefault()
event.preventDefault(); //就用preventDefault()
}
else{
event.returnValue=false; //兼容ie9以下
}
}
例2:阻止右键菜单默认行为
存在document的contextmenu事件中。
document.oncontextmenu=function(e){
if(e.preventDefault){ //有preventDefault()
e.preventDefault(); //就用preventDefault()
}
else{
e.returnValue=false; //兼容ie9以下
}
}