14_DOM绑定事件2.html 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. </head>
  8. <body>
  9. <div class="box">hello</div>
  10. <script>
  11. var oBox = document.getElementsByClassName("box")[0];
  12. // function foo(){
  13. // console.log("click");
  14. // // removeEventListener 移除事件 接受两个参数 第一个事件名称,第二个是事件处理函数(绑定和移除的必须是同一个函数,用匿名函数不可以)
  15. // oBox.removeEventListener("click",foo);
  16. // }
  17. // oBox.addEventListener("click",foo)
  18. // oBox.onclick = function(){
  19. // console.log(this.innerText);
  20. // }
  21. /*
  22. addEventListener绑定事件
  23. 接受两个参数 第一个是事件名称如:click、mouseenter... (注意:不用加 on)
  24. */
  25. // oBox.addEventListener("click",function(){
  26. // console.log(this.innerText);
  27. // })
  28. // oBox.addEventListener("mouseenter",function(){
  29. // console.log(this.innerText);
  30. // })
  31. var oHtml = document.documentElement;
  32. // 鼠标按下事件
  33. // oHtml.onmousedown = function(){
  34. // console.log("down")
  35. // }
  36. // 鼠标移动事件
  37. // oHtml.onmousemove =function(){
  38. // console.log("move")
  39. // }
  40. // 鼠标抬起事件
  41. // oHtml.onmouseup = function(){
  42. // console.log("up");
  43. // }
  44. function foo(e){
  45. console.log(e.clientX,e.clientY)
  46. }
  47. // oHtml.addEventListener("mousedown",function(){
  48. // oHtml.addEventListener("mousemove",foo)
  49. // oHtml.addEventListener("mouseup",function(){
  50. // oHtml.removeEventListener("mousemove",foo)
  51. // })
  52. // })
  53. oHtml.onmousedown = function(){
  54. oHtml.onmousemove = function(e){
  55. console.log(e.clientX,e.clientY)
  56. }
  57. oHtml.onmouseup = function(){
  58. oHtml.onmousemove = null;
  59. }
  60. }
  61. </script>
  62. </body>
  63. </html>