1.事件流概念:

捕获阶段:从外往里走的阶段;

目标阶段:到达目标了;

冒泡阶段:从目标离开,往外走;

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>事件流</title>
  <style>
    #grandfa {
      width: 600px;
      height: 600px;
      border: 1px solid #000;
    }
    #father {
      width: 400px;
      height: 400px;
      border: 1px solid #000;
    }
    #son {
      width: 200px;
      height: 200px;
      border: 1px solid #000;
    }
  </style>
</head>
<body>
  <div id="grandfa">
    <div id="father">
      <div id="son"></div>
    </div>
  </div>
  <script>
    var grandfa = document.getElementById('grandfa')
    var father = document.getElementById('father')
    var son = document.getElementById('son')
    grandfa.onclick = function () {
      console.log('grandfa点击事件')
    }
    father.onclick = function () {
      console.log('father点击事件')
    }
    son.onclick = function () {
      console.log('son点击事件')
    }
  </script>
</body>
</html>

2.事件委托:本来是自己做的事,委托给父级元素

 var ul=document.getElementById('ul')
   ul.addEventListener('click',fn,false)
   function fn(e){
    console.log(e.target.innerText )
   }

3.e.stopPropagation();  阻止事件传播

<div id="father">
        <div id="son"></div>
    </div>
let father = document.getElementById("father")
let son = document.getElementById("son")
father.onclick=function(){
    console.log('father')
}
son.onclick=function(e){
    console.log('son')
e.stopPropagation()
}

4.e.preventDefault() 阻止默认行为

 var box = document.getElementById('box')
   box.addEventListener('click',function(e){
     console.log(1)
e.preventDefault()
//  return false;  //在addEventListener不能使用return false来阻止默认行为
   })

 

  

posted on 2019-10-03 01:11  宅到深夜  阅读(213)  评论(0)    收藏  举报