14_DOM绑定事件2.html 2.5 KB

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