5_DOM_绑定事件.html 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. .box{
  9. width: 100px;
  10. height: 50px;
  11. background-color: red;
  12. text-align: center;
  13. line-height: 50px;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div class="box">按钮</div>
  19. <script>
  20. var oBox = document.getElementsByClassName("box")[0];
  21. // console.log(oBox[0]);
  22. // 通过on 绑定事件 on + 事件名称 = 事件处理函数
  23. // click 点击事件 当用户点击某一个元素的时候触发
  24. // on 绑定事件仅能绑定一个事件 如果多次绑定 则后面的会覆盖前面的
  25. // oBox.onclick = function(){
  26. // console.log("点击了按钮");
  27. // }
  28. // oBox.onclick = function(){
  29. // console.log("又点击了按钮");
  30. // }
  31. // oBox.onclick = null; // 取消点击事件
  32. // 通过addEventListener 来绑定事件
  33. // addEventListener 后面可以接两个参数 第一个参数是事件名称 第二个参数是事件处理函数
  34. // 事件名称不需要加on
  35. // addEventListener 可以对同一个标签绑定多次事件
  36. // oBox.addEventListener("click",function(){
  37. // console.log("通过addEventListener绑定点击事件");
  38. // });
  39. // oBox.addEventListener("click",function(){
  40. // console.log("又通过addEventListener绑定点击事件");
  41. // });
  42. // 取消通过addEventListener绑定的事件 使用removeEventListener 需要传入和绑定时一样的函数才可以取消成功
  43. var foo = function(){
  44. console.log("通过addEventListener绑定点击事件");
  45. };
  46. oBox.addEventListener("click",foo);
  47. oBox.removeEventListener("click",foo);
  48. </script>
  49. </body>
  50. </html>