2012-04-20 129 views
2

我已經制作了一個不使用jquery ui庫的可拖動div,但是我想讓可拖動框不離開它的容器。限制容器內的可拖動元素

這裏是我的demo

$(document).ready(function() { 
    var $dragging = null; 

    $(document.body).on("mousemove", function(e) { 
     if ($dragging) { 
      $dragging.offset({ 
       top: e.pageY, 
       left: e.pageX 
      }); 
     } 
    }); 

    $(document.body).on("mousedown", ".box", function (e) { 
     $dragging = $(e.target); 
    }); 

    $(document.body).on("mouseup", function (e) { 
     $dragging = null; 
    }); 
});​ 

如何做到這一點?請注意,我沒有使用JQUERY UI

回答

1

只要確保...

  • 框的左邊位置比容器的左側位置更大,且
  • 的正確位置(左位+框寬度)小於容器的正確位置,並
  • 盒子的頂部位置高於所述容器的頂部位置時,和
  • (頂部位置+框高度的底部位置)小於容器

http://jsfiddle.net/KdehU/2/

$(document).ready(function() { 
    var $dragging = null; 

    var container = $('#container'), 
     c_t = container.offset().top, 
     c_l = container.offset().left, 
     c_b = c_t + container.height(), 
     c_r = c_l + container.width(); 

    $(document.body).on("mousemove", function(e) { 
     if ($dragging) { 
      var width = $dragging.width(); 
      var height = $dragging.height(); 

      var new_y = (e.pageY > c_t && (e.pageY + height) < c_b) ? e.pageY : undefined; 
      var new_x = (e.pageX > c_l && (e.pageX + width) < c_r) ? e.pageX : undefined; 

      $dragging.offset({ 
       top: new_y, 
       left: new_x 
      }); 
     } 
    }); 

    $(document.body).on("mousedown", ".box", function (e) { 
     $dragging = $(e.target); 
    }); 

    $(document.body).on("mouseup", function (e) { 
     $dragging = null; 
    }); 
}); 
的底部位置
相關問題