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

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. var x = e.clientX;
  23. var y = e.clientY;
  24. var boxTop = oBox.offsetTop;
  25. var boxLeft = oBox.offsetLeft;
  26. var thisTop = y - boxTop;
  27. var thisLeft = x - boxLeft;
  28. oDom.onmousemove = function (e) {
  29. oBox.style.top = e.clientY - thisTop + "px";
  30. oBox.style.left = e.clientX - thisLeft + "px";
  31. console.log("move")
  32. }
  33. }
  34. oBox.onmouseup = function () {
  35. oDom.onmousemove = null;
  36. }
  37. </script>
  38. </body>
  39. </html>