jQuery.Drag.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. (function($){
  2. var O = 'opacity',
  3. C = 'CursorMove',
  4. M = 'mousemove.drag',
  5. U = 'mouseup.drag',
  6. D = 'mousedown.drag',
  7. W = $(window),
  8. A = $(document),
  9. timer = null,
  10. E = function () {
  11. this.w.css(O, 1);
  12. A.unbind(M+' '+U);
  13. },
  14. G = function (e) {
  15. var m = this,
  16. p = m.w.offset(),
  17. t = p.top,
  18. l = p.left,
  19. r = W.width() - m.w.outerWidth(),
  20. b = W.height() - m.w.outerHeight(),
  21. X = e.pageX,
  22. Y = e.pageY,
  23. x = m.p.left + (X - m.x) - W.scrollLeft(),
  24. y = m.p.top + (Y - m.y) - W.scrollTop();
  25. //以下逻辑保证在可视范围内移动
  26. if (l <= 0 && X < m.x)
  27. {
  28. x = 0;
  29. m.x = Math.max(X, 0);
  30. m.p.left = 0;
  31. }
  32. if (t <= 0 && Y < m.y)
  33. {
  34. y = 0;
  35. m.y = Math.max(Y, 0);
  36. m.p.top = 0;
  37. }
  38. if (r <= l - A.scrollLeft() && X > m.x)
  39. {
  40. x = r;
  41. m.x = Math.min(X, r);
  42. m.p.left = r;
  43. }
  44. if (b <= t - A.scrollLeft() && Y > m.y)
  45. {
  46. y = b;
  47. m.y = Math.min(Y, b);
  48. m.p.top = b;
  49. }
  50. m.w.css({ left : x, top : y });
  51. return false;
  52. },
  53. S = function (e, m) {
  54. e.preventDefault();
  55. m = this;
  56. m.w.css(O, 0.8);
  57. m.p = m.w.offset();
  58. m.x = e.pageX;
  59. m.y = e.pageY;
  60. A.bind(M, $.proxy(G, m)).bind(U, $.proxy(E, m));
  61. };
  62. $.fn.Drag = function(o){
  63. return this.each(function () {
  64. var e = $(this),
  65. x = function () {
  66. this.h = o ? (typeof o === 'string' ? $(o, e[0]) : o) : e;
  67. this.w = e;
  68. return this;
  69. },
  70. X = new x();
  71. e.data('__h', X.h);
  72. X.h.addClass(C).unbind(D).bind(D, $.proxy(S, X));
  73. });
  74. };
  75. $.fn.unDrag = function () {
  76. return this.each(function(){
  77. ($(this).data('__h') || $()).removeClass(C).unbind(D);
  78. });
  79. };
  80. })($);