10.拖拽.html 977 B

1234567891011121314151617181920212223242526272829303132333435
  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: 300px;
  10. height: 300px;
  11. background: aqua;
  12. position: absolute;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div id="box"></div>
  18. <script>
  19. var box = document.getElementById("box");
  20. // console.log(box.offsetLeft)
  21. // console.log(box.offsetTop)
  22. box.onmousedown = function(event) {
  23. var xLeft = event.clientX - box.offsetLeft;
  24. var yTop = event.clientY - box.offsetTop;
  25. box.onmousemove = function(event) {
  26. box.style.top = event.clientY - yTop + 'px';
  27. box.style.left = event.clientX - xLeft + 'px';
  28. }
  29. }
  30. box.onmouseup = function() {
  31. box.onmousemove = null;
  32. }
  33. </script>
  34. </body>
  35. </html>