13.拖拽.html 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. }
  14. </style>
  15. </head>
  16. <body>
  17. <!--
  18. e.clientX 事件发生时,鼠标在客户端区域的X坐标,客户端区域是指页面可视区域
  19. e.clientY 事件发生时,鼠标在客户端区域的Y坐标
  20. -->
  21. <div class="box"></div>
  22. <script>
  23. var box = document.querySelector(".box");
  24. console.log(box.offsetLeft);
  25. box.onmousedown = function(event) {
  26. var left1 = event.clientX - box.offsetLeft;
  27. var top1 = event.clientY - box.offsetTop;
  28. box.onmousemove = function(event){
  29. box.style.top = event.clientY - top1 + 'px';
  30. box.style.left = event.clientX - left1 + 'px';
  31. }
  32. }
  33. box.onmouseup = function() {
  34. box.onmousemove = null;
  35. }
  36. </script>
  37. </body>
  38. </html>