06.事件相关的练习-拖拽.html 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 () {
  37. //为document绑定一个onmousemove事件
  38. document.onmousemove = function (event) {
  39. event = event || window.event;
  40. //当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
  41. //获取鼠标的坐标
  42. var left = event.clientX;
  43. var top = event.clientY;
  44. //修改box1的位置
  45. box1.style.left = left + "px";
  46. box1.style.top = top + "px";
  47. };
  48. //为元素绑定一个鼠标松开事件
  49. document.onmouseup = function () {
  50. //当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
  51. //取消document的onmousemove事件
  52. document.onmousemove = null;
  53. //取消document的onmouseup事件
  54. document.onmouseup = null;
  55. // alert("鼠标松开了");
  56. };
  57. };
  58. };
  59. </script>
  60. </head>
  61. <body>
  62. <div id="box1"></div>
  63. <div id="box2"></div>
  64. </body>
  65. </html>