16.拖拽.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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: yellowgreen;
  12. cursor: pointer;
  13. margin-left: 20px;
  14. position: absolute;
  15. /* left: 300px; */
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="box"></div>
  21. <script>
  22. var box = document.getElementById("box");
  23. box.onmousedown = function(event) {
  24. console.log(event)
  25. // event.clientX event.clintY 事件触发时 鼠标所在的X,Y坐标
  26. // 计算鼠标在元素内部的偏移量
  27. var left1 = event.clientX - box.offsetLeft;
  28. var top1 = event.clientY - box.offsetTop;
  29. // 移动事件 绑定给document
  30. document.onmousemove = function(event) {
  31. box.style.left = event.clientX - left1 + 'px';
  32. box.style.top = event.clientY - top1 + 'px';
  33. }
  34. }
  35. // 抬起事件
  36. document.onmouseup = function() {
  37. document.onmousemove = null;
  38. }
  39. </script>
  40. </body>
  41. </html>