pc端移动端拖拽实现

曾经终败给现在 2021-12-21 23:47 537阅读 0赞
  1. #div1 {
  2. width: 100px;
  3. height: 100px;
  4. background: red;
  5. position: absolute;
  6. }

  html

  1. <div id="div1">
  2. </div>

  js

  1. 1 window.onload = function () {
  2. 2 var oDiv = document.getElementById('div1');
  3. 3 //pc端
  4. 4 oDiv.onmousedown = function (ev) {
  5. 5 var oEvent = ev || event; //需要获取和事件相关的信息时使用
  6. 6 var disX = oEvent.clientX - oDiv.offsetLeft;
  7. 7 var disY = oEvent.clientY - oDiv.offsetTop;
  8. 8
  9. 9 document.onmousemove = function (ev) {
  10. 10 var oEvent = ev || event;
  11. 11 var l = oEvent.clientX - disX;
  12. 12 var t = oEvent.clientY - disY;
  13. 13
  14. 14 if (l < 0) {
  15. 15 l = 0;
  16. 16 } else if (l > document.documentElement.clientWidth - oDiv.offsetWidth) {
  17. 17 l = document.documentElement.clientWidth - oDiv.offsetWidth;
  18. 18 }
  19. 19
  20. 20 if (t < 0) {
  21. 21 t = 0;
  22. 22 } else if (t > document.documentElement.clientHeight - oDiv.offsetHeight) {
  23. 23 t = document.documentElement.clientHeight - oDiv.offsetHeight;
  24. 24 }
  25. 25
  26. 26 oDiv.style.left = l + 'px';
  27. 27 oDiv.style.top = t + 'px';
  28. 28 };
  29. 29
  30. 30 document.onmouseup = function () {
  31. 31 document.onmousemove = null;
  32. 32 document.onmouseup = null;
  33. 33 };
  34. 34 };
  35. 35 //移动端
  36. 36 // 拖拽
  37. 37 // 获取节点
  38. 38 var block = document.getElementById("right");
  39. 39 var oW, oH;
  40. 40 // 绑定touchstart事件
  41. 41 oDiv.addEventListener("touchstart", function (e) {
  42. 42 var touches = e.touches[0];
  43. 43 oW = touches.clientX - oDiv.offsetLeft;
  44. 44 oH = touches.clientY - oDiv.offsetTop;
  45. 45 //阻止页面的滑动默认事件
  46. 46 document.addEventListener("touchmove", defaultEvent, false);
  47. 47 }, false);
  48. 48 oDiv.addEventListener("touchmove", function (e) {
  49. 49 var touches = e.touches[0];
  50. 50 var oLeft = touches.clientX - oW;
  51. 51 var oTop = touches.clientY - oH;
  52. 52 if (oLeft < 0) {
  53. 53 oLeft = 0;
  54. 54 } else if (oLeft > document.documentElement.clientWidth - oDiv.offsetWidth) {
  55. 55 oLeft = (document.documentElement.clientWidth - oDiv.offsetWidth);
  56. 56 }
  57. 57 oDiv.style.left = oLeft + "px";
  58. 58 oDiv.style.top = oTop + "px";
  59. 59 }, false);
  60. 60 oDiv.addEventListener("touchend", function () {
  61. 61 document.removeEventListener("touchmove", defaultEvent, false);
  62. 62 }, false);
  63. 63
  64. 64 function defaultEvent(e) {
  65. 65 e.preventDefault();
  66. 66 };
  67. 67 };

转载于:https://www.cnblogs.com/NB-JDzhou/p/8430142.html

发表评论

表情:
评论列表 (有 0 条评论,537人围观)

还没有评论,来说两句吧...

相关阅读