07.事件相关的练习-拖拽二.html 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #box1 {
  10. width: 100px;
  11. height: 100px;
  12. background-color: red;
  13. position: absolute;
  14. }
  15. #box2{
  16. width: 100px;
  17. height: 100px;
  18. background-color: yellow;
  19. position: absolute;
  20. left: 200px;
  21. top: 200px;
  22. }
  23. </style>
  24. <script>
  25. window.onload = function () {
  26. /**
  27. * 拖拽box1元素
  28. * -拖拽的流程
  29. * 1.当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown
  30. * 2.当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
  31. * 3.当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
  32. */
  33. //获取box1
  34. var box1 = document.getElementById("box1");
  35. //为box1绑定一个鼠标按下事件
  36. box1.onmousedown = function (event) {
  37. event = event || window.event;
  38. //div的偏移量 鼠标.clientX - 元素.offsetLeft
  39. //div的偏移量 鼠标.clientY - 元素.offsetTop
  40. var ol = event.clientX - box1.offsetLeft;
  41. var ot = event.clientY - box1.offsetTop;
  42. //为document绑定一个onmousemove事件
  43. document.onmousemove = function (event) {
  44. event = event || window.event;
  45. //当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
  46. //获取鼠标的坐标
  47. var left = event.clientX-ol;
  48. var top = event.clientY-ot;
  49. //修改box1的位置
  50. box1.style.left = left + "px";
  51. box1.style.top = top + "px";
  52. };
  53. //为元素绑定一个鼠标松开事件
  54. document.onmouseup = function () {
  55. //当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
  56. //取消document的onmousemove事件
  57. document.onmousemove = null;
  58. //取消document的onmouseup事件
  59. document.onmouseup = null;
  60. // alert("鼠标松开了");
  61. };
  62. };
  63. };
  64. </script>
  65. </head>
  66. <body>
  67. <div id="box1"></div>
  68. <div id="box2"></div>
  69. </body>
  70. </html>