8.拖拽.html 1010 B

1234567891011121314151617181920212223242526272829303132333435363738
  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: 200px;
  10. height: 200px;
  11. background: #00f;
  12. position: absolute;
  13. /* left: 1px; */
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div id="box"></div>
  19. <script>
  20. var box = document.getElementById("box");
  21. box.onmousedown = function(e) {
  22. var x = e.clientX - box.offsetLeft;
  23. var y = e.clientY - box.offsetTop;
  24. console.log(x,y)
  25. box.onmousemove = function(e) {
  26. var x1 = e.clientX;
  27. var y1 = e.clientY;
  28. console.log(x1)
  29. box.style.left = x1 - x + 'px';
  30. box.style.top = y1 - y + 'px';
  31. }
  32. }
  33. box.onmouseup = function() {
  34. box.onmousemove = null;
  35. }
  36. </script>
  37. </body>
  38. </html>