DOM event of the difference between target and currentTarget

DOM events targetand currentTargetthe difference

  • targetIt is an event-triggered real element

  • currentTargetIs the event binding element

  • Event handler in thispoint is forcurrentTarget

  • currentTargetAnd target, sometimes one and the same element, and sometimes not the same element (because the event bubbling)

    • When an event is triggered child element, currentTargetthe element binding events, targetas child elements
    • When the event is triggered when the element itself, currentTargetand targetfor the same element.
<body>
   <ul id="box">
       <Li id="apple">苹果</Li>
       <li>香蕉</li>
       <li>桃子</li>
   </ul>
</body>
<script type="text/javascript">
   var box = document.getElementById('box');
   var apple = document.getElementById('apple');

   //直接绑定在目标元素apple上
   apple.onclick = function (e){  
       console.log(e.target);          //<li id="apple">苹果</li>
       console.log(e.currentTarget);    //<li id="apple">苹果</li>
       console.log(this);               //<li id="apple">苹果</li>
       console.log(e.target === e.currentTarget);      //true
       console.log(e.target === this);           //true
   } 

  //绑定在父元素box上(如果点击apple这个li时)
   box.onclick = function (e){
       console.log(e.target);           // <li id="apple">苹果</li>
       console.log(e.currentTarget);       //<ul id="box">...</ul>
       console.log(this);                  //<ul id="box">...</ul>
       console.log(e.currentTarget===this);      //true
       console.log(e.target === e.currentTarget);        //false
       console.log(e.target === this);           //false
   }

</script>

Guess you like

Origin www.cnblogs.com/guojbing/p/12213332.html