10.拖拽.html 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  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: #0f0;
  12. position: absolute;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div id="box"></div>
  18. <script>
  19. // clientX 鼠标在客户端的X轴位置
  20. // clientY 鼠标在客户端的Y轴位置
  21. var box = document.getElementById("box");
  22. box.onmousedown = function(event) {
  23. console.log(event)
  24. // box.style.left = 330 + 'px';
  25. var left1 = event.clientX - box.offsetLeft;
  26. var top1 = event.clientY - box.offsetTop;
  27. box.onmousemove = function(event) {
  28. box.style.left = event.clientX - left1 + 'px';
  29. box.style.top = event.clientY - top1 + 'px';
  30. }
  31. }
  32. box.onmouseup = function() {
  33. box.onmousemove = null;
  34. }
  35. </script>
  36. </body>
  37. </html>