Drag.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //获取相关CSS属性
  2. const getCss = function (o: any, key: any) {
  3. return o.currentStyle
  4. ? o.currentStyle[key]
  5. : document.defaultView?.getComputedStyle(o, null)[key];
  6. };
  7. const params = {
  8. left: 0,
  9. top: 0,
  10. currentX: 0,
  11. currentY: 0,
  12. flag: false,
  13. } as any;
  14. const startDrag = function (bar: any, target: any, callback?: any) {
  15. const screenWidth = document.body.clientWidth; // body当前宽度
  16. const screenHeight = document.documentElement.clientHeight; // 可见区域高度
  17. const dragDomW = target.offsetWidth; // 对话框宽度
  18. const dragDomH = target.offsetHeight; // 对话框高度
  19. const minDomLeft = target.offsetLeft;
  20. const minDomTop = target.offsetTop;
  21. const maxDragDomLeft = screenWidth - minDomLeft - dragDomW;
  22. const maxDragDomTop = screenHeight - minDomTop - dragDomH;
  23. if (getCss(target, 'left') !== 'auto') {
  24. params.left = getCss(target, 'left');
  25. }
  26. if (getCss(target, 'top') !== 'auto') {
  27. params.top = getCss(target, 'top');
  28. }
  29. //o是移动对象
  30. bar.onmousedown = function (event: any) {
  31. params.flag = true;
  32. if (!event) {
  33. event = window.event;
  34. //防止IE文字选中
  35. bar.onselectstart = function () {
  36. return false;
  37. };
  38. }
  39. const e = event;
  40. params.currentX = e.clientX;
  41. params.currentY = e.clientY;
  42. };
  43. document.onmouseup = function () {
  44. params.flag = false;
  45. if (getCss(target, 'left') !== 'auto') {
  46. params.left = getCss(target, 'left');
  47. }
  48. if (getCss(target, 'top') !== 'auto') {
  49. params.top = getCss(target, 'top');
  50. }
  51. };
  52. document.onmousemove = function (event) {
  53. const e: any = event ? event : window.event;
  54. if (params.flag) {
  55. const nowX = e.clientX,
  56. nowY = e.clientY;
  57. const disX = nowX - params.currentX,
  58. disY = nowY - params.currentY;
  59. let left = parseInt(params.left) + disX;
  60. let top = parseInt(params.top) + disY;
  61. // 拖出屏幕边缘
  62. if (-left > minDomLeft) {
  63. left = -minDomLeft;
  64. } else if (left > maxDragDomLeft) {
  65. left = maxDragDomLeft;
  66. }
  67. if (-top > minDomTop) {
  68. top = -minDomTop;
  69. } else if (top > maxDragDomTop) {
  70. top = maxDragDomTop;
  71. }
  72. target.style.left = left + 'px';
  73. target.style.top = top + 'px';
  74. if (typeof callback == 'function') {
  75. callback((parseInt(params.left) || 0) + disX, (parseInt(params.top) || 0) + disY);
  76. }
  77. if (event.preventDefault) {
  78. event.preventDefault();
  79. }
  80. return false;
  81. }
  82. };
  83. };
  84. export default startDrag;