drag.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * 拖拽移动
  3. * @param {elementObjct} bar 鼠标点击控制拖拽的元素
  4. * @param {elementObjct} target 移动的元素
  5. * @param {function} callback 移动后的回调
  6. */
  7. export function startDrag(bar, target, callback) {
  8. var params = {
  9. top: 0,
  10. left: 0,
  11. currentX: 0,
  12. currentY: 0,
  13. flag: false,
  14. cWidth: 0,
  15. cHeight: 0,
  16. tWidth: 0,
  17. tHeight: 0
  18. };
  19. // 给拖动块添加样式
  20. bar.style.cursor = 'move';
  21. // 获取相关CSS属性
  22. // o是移动对象
  23. // var getCss = function (o, key) {
  24. // return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
  25. // };
  26. bar.onmousedown = function (event) {
  27. // 按下时初始化params
  28. var e = event ? event : window.event;
  29. params = {
  30. top: target.offsetTop,
  31. left: target.offsetLeft,
  32. currentX: e.clientX,
  33. currentY: e.clientY,
  34. flag: true,
  35. cWidth: document.body.clientWidth,
  36. cHeight: document.body.clientHeight,
  37. tWidth: target.offsetWidth,
  38. tHeight: target.offsetHeight
  39. };
  40. // 给被拖动块初始化样式
  41. target.style.margin = 0;
  42. target.style.top = params.top + 'px';
  43. target.style.left = params.left + 'px';
  44. if (!event) {
  45. // 防止IE文字选中
  46. bar.onselectstart = function () {
  47. return false;
  48. }
  49. }
  50. document.onmousemove = function (event) {
  51. // 防止文字选中
  52. window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
  53. var e = event ? event : window.event;
  54. if (params.flag) {
  55. var nowX = e.clientX;
  56. var nowY = e.clientY;
  57. // 差异距离
  58. var disX = nowX - params.currentX;
  59. var disY = nowY - params.currentY;
  60. // 最终移动位置
  61. var zLeft = 0;
  62. var zTop = 0;
  63. zLeft = parseInt(params.left) + disX;
  64. // 限制X轴范围
  65. if (zLeft <= -parseInt(params.tWidth / 2)) {
  66. zLeft = -parseInt(params.tWidth / 2);
  67. }
  68. if (zLeft >= params.cWidth - parseInt(params.tWidth * 0.5)) {
  69. zLeft = params.cWidth - parseInt(params.tWidth * 0.5);
  70. }
  71. zTop = parseInt(params.top) + disY;
  72. // 限制Y轴范围
  73. if (zTop <= 0) {
  74. zTop = 0;
  75. }
  76. if (zTop >= params.cHeight - parseInt(params.tHeight * 0.5)) {
  77. zTop = params.cHeight - parseInt(params.tHeight * 0.5);
  78. }
  79. // 执行移动
  80. target.style.left = zLeft + 'px';
  81. target.style.top = zTop + 'px';
  82. }
  83. if (typeof callback == "function") {
  84. callback(zLeft, zTop);
  85. }
  86. }
  87. document.onmouseup = function () {
  88. params.flag = false;
  89. document.onmousemove = null;
  90. document.onmouseup = null;
  91. };
  92. };
  93. }