08.事件相关的练习-拖拽三.html 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. //设置box1捕获所有鼠标按下的事件
  38. /**
  39. * setCapture()
  40. * -只有IE支持,但是在火狐中调用时不会报错,
  41. * 而如果使用Chrome调用,会报错
  42. */
  43. if (box1.setCapture) {
  44. box1.setCapture();
  45. };
  46. //也可以写成下面的格式,更简洁
  47. box1.setCapture && box1.setCapture();
  48. // box1.setCapture();//Edge不可用
  49. event = event || window.event;
  50. //div的偏移量 鼠标.clientX - 元素.offsetLeft
  51. //div的偏移量 鼠标.clientY - 元素.offsetTop
  52. var ol = event.clientX - box1.offsetLeft;
  53. var ot = event.clientY - box1.offsetTop;
  54. //为document绑定一个onmousemove事件
  55. document.onmousemove = function (event) {
  56. event = event || window.event;
  57. //当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
  58. //获取鼠标的坐标
  59. var left = event.clientX - ol;
  60. var top = event.clientY - ot;
  61. //修改box1的位置
  62. box1.style.left = left + "px";
  63. box1.style.top = top + "px";
  64. };
  65. //为元素绑定一个鼠标松开事件
  66. document.onmouseup = function () {
  67. //当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
  68. //取消document的onmousemove事件
  69. document.onmousemove = null;
  70. //取消document的onmouseup事件
  71. document.onmouseup = null;
  72. // alert("鼠标松开了");
  73. //当鼠标松开时,取消对事件的捕获
  74. box1.releaseCapture && box1.releaseCapture();
  75. };
  76. /**
  77. * 当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容,
  78. * 此时会导致拖拽功能的异常,这个是浏览器提供的默认行为
  79. * 如果不希望发生这个行为,则可以通过return false来取消默认行为
  80. *
  81. * 但是这个方法对IE8不起作用
  82. */
  83. return false;
  84. };
  85. };
  86. </script>
  87. </head>
  88. <body>
  89. 我是一段文字
  90. <div id="box1"></div>
  91. <div id="box2"></div>
  92. </body>
  93. </html>