jQuery事件打破可拖动的遏制 [英] Jquery event for breaking draggable containment

查看:87
本文介绍了jQuery事件打破可拖动的遏制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为可拖动项破坏其收容时添加一个回调.我有这个功能:

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?

推荐答案

将元素放到另一个元素的4个角上时,您可以检查元素的4个角,以查看是否有任何角在该元素内,然后执行从那时起您想要什么.

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).

以下是您可以使用的示例(我在此处使用了console.log

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>

这篇关于jQuery事件打破可拖动的遏制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆