drag.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * v-dialogDrag 弹窗拖拽
  3. * Copyright (c) 2019 ruoyi
  4. */
  5. // 当前设备
  6. const isDevice = localStorage.getItem('isDevice');
  7. export default {
  8. bind(el, binding, vnode, oldVnode) {
  9. const value = binding.value;
  10. if (value == false) return;
  11. if (isDevice == 'PC') return;
  12. let initialTouchX = 0;
  13. let initialTouchY = 0;
  14. let initialLeft = 0;
  15. let initialTop = 0;
  16. el.addEventListener(
  17. 'touchstart',
  18. (e) => {
  19. // e.preventDefault();
  20. e.stopPropagation();
  21. e.currentTarget.style.touchAction = 'none';
  22. const touch = e.touches[0];
  23. initialTouchX = touch.clientX;
  24. initialTouchY = touch.clientY;
  25. initialLeft = e.currentTarget.offsetLeft;
  26. initialTop = e.currentTarget.offsetTop;
  27. },
  28. false
  29. );
  30. el.addEventListener(
  31. 'touchmove',
  32. function (e) {
  33. e.preventDefault();
  34. e.stopPropagation();
  35. const clientX = e.targetTouches[0].clientX;
  36. const clientY = e.targetTouches[0].clientY;
  37. // 限制拖拽范围
  38. const clientWidth = document.documentElement.clientWidth;
  39. const clientHeight = document.documentElement.clientHeight;
  40. // 计算边界限制
  41. const maxLeft = clientWidth - this.offsetWidth;
  42. const maxTop = clientHeight - this.offsetHeight;
  43. // 计算基于初始位置的移动量并应用边界限制
  44. const deltaX = clientX - initialTouchX;
  45. const deltaY = clientY - initialTouchY;
  46. const left = initialLeft + deltaX;
  47. const top = initialTop + deltaY;
  48. // 添加边界限制
  49. this.style.left = `${Math.max(0, Math.min(left, maxLeft))}px`;
  50. this.style.top = `${Math.max(0, Math.min(top, maxTop))}px`;
  51. localStorage.setItem(this.className, JSON.stringify([this.style.left, this.style.top]));
  52. },
  53. false
  54. );
  55. el.addEventListener('touchend', function (e) {}, false);
  56. },
  57. };