Jquery event for breaking draggable containment

五迷三道 提交于 2019-12-11 06:24:15

问题


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>


来源:https://stackoverflow.com/questions/38806326/jquery-event-for-breaking-draggable-containment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!