Jquery event for breaking draggable containment

2019-07-31 16:29发布

问题:

I want to add a callback for when a draggable item breaks it's containment. I have this function:

function makeDraggable(){
    $( ".draggable" ).draggable({ containment: "parent" , grid: [ 25, 25 ] });
}

Is there a simple way to achieve this, without using collision detection? If not, how would I go about doing the collision detection?

回答1:

You can check the 4 corners of the element when it is dropped against the 4 corners of another element to see if any of the corners are inside that element and do whatever you want from that point.

The problem with containment is that the drag can be done only within that containment (you cannot drag the element outside that containment).

Here is an example you can use (I used the console.log there

$(function() {
  $("#draggable").draggable({
    stop: function( event, ui ) {
      droppapleBox = $('#droppable-area')[0].getBoundingClientRect()
      draggableBox = ui.helper[0].getBoundingClientRect()
      if (draggableBox.left > droppapleBox.right || draggableBox.right < droppapleBox.left || draggableBox.top > droppapleBox.bottom || draggableBox.bottom < droppapleBox.top) {
        console.log('Element dropped completely outside the drop area');
      } else {
        console.log('Element dropped inside the drop area');
      }
    }
  });
});
body {
  font-family: arial;
  font-size: 12px;
}
.drag-box {
  width: 50px;
  height: 50px;
}

.drop-box {
  width: 150px;
  height: 150px;
  margin-left: 70px;
  margin-top: 70px;
  margin-bottom: 250px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<body>
 
<div id="droppable-area" class="drop-box ui-widget-header">
  <p>Drop me here</p>
  <div id="draggable" class="drag-box ui-widget-content">
    <p>Drag Me</p>
  </div>
</div>