2010-10-06 39 views
2

我試圖授權拖出一個對象只在他的收容的右側或底側,並不能做到這一點,不要停止拖動元素。Draggable和可擴展的遏制

我的代碼:

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
    #parent { height: 500px; width: 500px; border: 1px black solid; } 
    #images { height: 100px; width: 100px; background-color:orange; } 
    </style> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js"></script> 
</head> 
<body> 
<div id="parent"> 
    <div id="images"></div> 
</div> 
<script> 
$(document).ready(function() { 
    $("#images").draggable({ 
     containment: $("#parent"), 
     drag: function(event, ui) { 
      var helper = ui.helper, pos = ui.position; 
      if(pos.left + parseInt(helper.outerWidth(), 10) == parseInt($("#parent").css("width"), 10)) { 
       $("#parent").animate({width: "+=100"}); 
      } 
      if(pos.top + parseInt(helper.outerHeight(), 10) == parseInt($("#parent").css("height"), 10)) { 
       $("#parent").animate({height: "+=100"}); 
      } 
     } 
    }); 
}); 
</script> 
</body> 
</html> 

你有一個想法,怎麼樣才能繼續拖動右側或底部刷新遏制大小?

謝謝!

+0

你能獎勵賞金,如果你高興我的解決方案?如果沒有人會爲我的答案投票,那麼50分就會蒸發到以太。 :( – Thomas 2010-10-16 17:41:47

回答

8

簡單的解決方案(見DEMO):

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
    #parent { height: 300px; width: 300px; border: 1px black solid; position: relative; left: 0; } 
    #images { height: 100px; width: 100px; background-color:orange; } 
    </style> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js"></script> 
</head> 
<body> 
<div id="parent"> 
    <div class="container"> 
     <div id="images"></div> 
    </div> 
</div> 
<script> 
$(document).ready(function() { 
    var 
     $document = $(document), 
     $parent = $("#parent"), 
     $container = $(".container", $parent), 
     offset = $container.offset(), 
     scrollbarSafety = 15; // use this to avoid dragging outside of window, thus creating scrollbars and wreaking all kinds of havoc on draggables containment checks 

    $container 
     .width($document.width() - offset.left - scrollbarSafety) 
     .height($document.height() - offset.top - scrollbarSafety); 

    $("#images") 
      .draggable(
      { 
       containment: $container, 
       drag: 
        function(event, ui) 
        { 
         var 
          $draggee = $(this), 
          draggeePosition = $draggee.position(), 
          shouldWidth = draggeePosition.left + $draggee.width(), 
          shouldHeight = draggeePosition.top + $draggee.height(); 
         if($parent.width() < shouldWidth) 
         { 
          $parent.width(shouldWidth); 
         } 
         if($parent.height() < shouldHeight) 
         { 
          $parent.height(shouldHeight); 
         } 
      } 
      } 
     ); 
}); 
</script> 
</body> 
</html>