当前位置:网站首页>JS EventListener

JS EventListener

2022-06-27 08:17:00 SeriousLose

DOM2 Level event


Event flow can be selected . Multiple events of the same kind can be bound . The event name can form a string .

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="content"></div>
</body>
</html>

addEventListener

  • Add listening Events

    
      let content = document.getElementById("content");
      content.addEventListener("click", function () {
        console.log("seriousLose");
      }, false)
    
      content.addEventListener("click", function () {
        console.log("hello seriousLose");
      }, false)
    
  • Block default events preventDefault()

    document.body.addEventListener('touchmove', function (event) {
        event.preventDefault();
    },false);
    
  • Stop the event from bubbling stopPropagation()

    <div id="div"><button id="btn"> Button </button></div>
    
      function showType(event) {
        alert(event.type);
        event.stopPropagation();
      }
    
      function showDiv() {
        alert("div");
      }
      document.getElementById("btn").addEventListener("click", showType);
      document.getElementById("div").addEventListener("click", showDiv);
    

removeEventListener

  • Remove Events

      function add() {
        console.log("I me here seriousLose");
      }
      content.addEventListener("mouseenter", add, false);
      content.removeEventListener("mouseenter", add, false);
    

<aside> removeEventListener You need to know which event handler you need to remove . Anonymous function discards its own function name , It can't be removed .

</aside>

 content.addEventListener("click", function () {
    console.log("hello seriousLose");
  }, false)
  
 //  It's no use , Cannot be removed 
 content.removeEventListener("click", function () {
    console.log("hello seriousLose");
  }, false), false);

<aside> IE9 Following IE Browser does not support addEventListener() and removeEventListener(), Use attachEvent() And detachEvent() Instead of , because IE9 The following is not supported for event capture , So there's no third parameter , The first event name should be preceded by on

</aside>

demos/DW-dom.html at main · SeriousLose/demos

EventTarget.addEventListener() - Web API Interface reference | MDN

EventTarget.removeEventListener - Web API Interface reference | MDN

原网站

版权声明
本文为[SeriousLose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270803365153.html