JS,JQuery与vue 阻止事件冒泡与取消默认事件对比归纳
js中
阻止事件冒泡
JavaScript的事件默认冒泡到window, IE8-冒泡到document.
阻止事件冒泡:
元素.stopPropagation();
标准浏览器元素.cancelBubble = true;
IE浏览器
box.onclick = function (event) {
event.stopPropagation ? eeventstopPropagation() : event.cancelBubble = true;
}
取消默认事件
JavaScript不同的添加事件的方式,有不同的取消默认事件的方法
DOM0级事件:元素.事件添加的事件: return false
DOM2级事件:
元素.addEventListener():ev.preventDefault();
标准浏览器
元素.attachEvent():ev.returnValue=false;
标准浏览器
document.addEventListener("contextmenu",function(ev){
var ev = window.event || ev;
if(ev.preventDefault)ev.preventDefault();//绑定事件取消
},false);
JQ中
jQuery中有对应的方法阻止事件冒泡和取消默认事件
$("#box").click(function(ev){
ev.preventDefault();//阻止默认事件
ev.stopPropagation();//阻止事件冒泡
return false;//阻止默认事件+事件冒泡
});
vue中
阻止默认事件preventDefault
<!-- 阻止默认事件 -->
<div @contextmenu="menu" class="box"></div>
menu(e){
// 使用事件源阻止默认对象
e.preventDefault()
console.log(111);
}
阻止事件传播stopPropagation
<!-- 阻止事件传播 -->
<div class="outer" @click="outer">
<div class="inner" @click="inner">
</div>
</div>
inner(e){
// 使用事件对象源event阻止事件传播
e.stopPropagation()
console.log('inner');
}
事件修饰符
阻止默认事件.prevent
<!-- prevent阻止默认事件 -->
<button @contextmenu.prevent="add1">阻止默认事件</button>
<textarea @keydown.enter.prevent="enter" id="" cols="30" rows="10"></textarea>
add1(){
console.log('阻止默认事件');
},
enter(){
console.log('回车了');
}
阻止事件冒泡.stop
<!-- stop阻止事件传播 -->
<div class="outer" @click="outer">
<div class="inner" @click.stop="inner"></div>
</div>
outer(){
console.log('outer');
},
inner(){
console.log('inner');
}
阻止自己身上的冒泡行为.self
<!-- 案例 -->
<button @click="isShow = true">删除</button>
<div class="main" v-if="isShow" @click.self="isShow=false">
<div class="con">
<h2>确定要删除吗?</h2>
<div>
<button class="btn" @click="confirm">确定</button>
<button class="btn" @click="isShow=false">取消</button>
</div>
</div>
</div>