练习8_移动正方形.html 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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: 100px;
  11. background-color: red;
  12. position: absolute;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div id="box"></div>
  18. <script>
  19. // 第一步获取元素 正方形
  20. var oBox = document.getElementById("box");
  21. // 获取页面
  22. var oPage = document.documentElement;
  23. // 第二步给元素添加事件 给正方形绑定鼠标按下事件
  24. oBox.onmousedown = function(e){
  25. // 记录鼠标点击时在正方形的哪个位置
  26. var x = e.offsetX;
  27. var y = e.offsetY;
  28. // 第三步给页面绑定移动事件
  29. oPage.onmousemove = function(e){
  30. oBox.style.top = (e.clientY - y)+ "px";
  31. oBox.style.left = (e.clientX - x )+ "px";
  32. }
  33. }
  34. // 第四步移除页面移动事件
  35. oBox.onmouseup = function(){
  36. oPage.onmousemove = null;
  37. }
  38. </script>
  39. </body>
  40. </html>