今天來看看前端的冒泡和事件默認事件如何處理
1.event.stopPropagation()方法
這是阻止事件的冒泡方法,不讓事件向documen上蔓延,但是默認事件任然會執行,當你掉用這個方法的時候,如果點擊一個連接,這個連接仍然會被打開,
2.event.preventDefault()方法
這是阻止默認事件的方法,調用此方法是,連接不會被打開,但是會發生冒泡,冒泡會傳遞到上一層的父元素;
3.return false ;
這個方法比較暴力,他會同事阻止事件冒泡也會阻止默認事件;寫上此代碼,連接不會被打開,事件也不會傳遞到上一層的父元素;可以理解為return false就等於同時調用了event.stopPropagation()和event.preventDefault()
4.我們來看看幾組demo,使用jquery進行DOM操作
這是html代碼,div里面套了一個a標簽,連接到百度
- <div class="box1">
- <a href="http://www.baidu.com" target="_blank"></a>
- </div>
-
<div class="box1">
-
<a href="http://www.baidu.com" target="_blank"> </a>
-
</div>
- .box1{
- height: 200px;
- width: 600px;
- margin: 0 auto;
- }
- .box1 a{
- display: block;
- height: 50%;
- width: 50%;
- background:red;
- }
-
.box1{
-
height: 200px;
-
width: 600px;
-
margin: 0 auto;
-
}
-
.box1 a{
-
display: block;
-
height: 50%;
-
width: 50%;
-
background:red;
-
}
下面來看js代碼,第一種
- //不阻止事件冒泡和默認事件
- $(".box1").click(function(){
- console.log("1")//不阻止事件冒泡會打印1,頁面跳轉;
- });
-
//不阻止事件冒泡和默認事件
-
-
$(".box1").click(function(){
-
console.log("1")//不阻止事件冒泡會打印1,頁面跳轉;
-
});
第二種
- //阻止冒泡
- $(".box1 a").click(function(event){
- event.stopPropagation();//不會打印1,但是頁面會跳轉;
- });
- $(".box1").click(function(){
- console.log("1")
- });
-
//阻止冒泡
-
$(".box1 a").click(function(event){
-
event.stopPropagation();//不會打印1,但是頁面會跳轉;
-
-
});
-
-
$(".box1").click(function(){
-
console.log("1")
-
});
第三種
- $(".box1 a").click(function(event){
- //阻止默認事件
- event.preventDefault();//頁面不會跳轉,但是會打印出1,
- });
- $(".box1").click(function(){
- console.log("1");
- });
-
$(".box1 a").click(function(event){
-
//阻止默認事件
-
event.preventDefault();//頁面不會跳轉,但是會打印出1,
-
});
-
-
$(".box1").click(function(){
-
console.log("1");
-
});
event.stopPropagation()和event.preventDefault(),return false
第四種
- $(".box1").click(function(){
- console.log("1")
- });
- //阻止冒泡
- $(".box1 a").click(function(event){
- event.stopPropagation();
- //阻止默認事件
- event.preventDefault() //頁面不會跳轉,也不會打印出1
- })
-
$(".box1").click(function(){
-
console.log("1")
-
});
-
//阻止冒泡
-
$(".box1 a").click(function(event){
-
event.stopPropagation();
-
//阻止默認事件
-
event.preventDefault() //頁面不會跳轉,也不會打印出1
-
})
第五種
- $(".box1").click(function(){
- console.log("1")
- });
- $(".box1 a").click(function(event){
- return false; //頁面不會跳轉,也不會打印出1,等於同時調用了event.stopPropagation()和event.preventDefault()
- });
-
$(".box1").click(function(){
-
console.log("1")
-
});
-
$(".box1 a").click(function(event){
-
return false; //頁面不會跳轉,也不會打印出1,等於同時調用了event.stopPropagation()和event.preventDefault()
-
-
});