练习10_移动正方形.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 class="box"></div>
  18. <script>
  19. var oBox = document.getElementsByClassName("box")[0];
  20. var oDom = document.documentElement;
  21. oBox.onmousedown = function (e) {
  22. // 获取鼠标点击的位置
  23. var x = e.clientX;
  24. var y = e.clientY;
  25. // 获取盒子距离页面顶部的距离
  26. var boxTop = oBox.offsetTop;
  27. // 获取盒子距离页面左边的距离
  28. var boxLeft = oBox.offsetLeft;
  29. // 获取鼠标点击位置 在盒子里的位置
  30. var thisTop = y - boxTop;
  31. var thisLeft = x - boxLeft;
  32. oDom.onmousemove = function (e) {
  33. oBox.style.top = e.clientY - thisTop + "px";
  34. oBox.style.left = e.clientX - thisLeft + "px";
  35. console.log("move")
  36. }
  37. }
  38. oBox.onmouseup = function () {
  39. oDom.onmousemove = null;
  40. }
  41. </script>
  42. </body>
  43. </html>