Programmatically drag and drop element onto another element

旧城冷巷雨未停 提交于 2019-11-27 16:13:22

This is how the jQuery UI team programmatically trigger drop event.

droppable_events.js:

draggable = $( "#draggable1" ).draggable(),
droppable1 = $( "#droppable1" ).droppable( config ),
droppable2 = $( "#droppable2" ).droppable( config ),

droppableOffset = droppable1.offset(),
draggableOffset = draggable.offset(),
dx = droppableOffset.left - draggableOffset.left,
dy = droppableOffset.top - draggableOffset.top;

draggable.simulate( "drag", {
    dx: dx,
    dy: dy
});

The simulate function is defined in jquery.simulate.js. In simple words, it moves the draggable onto the droppable to trigger the drop event.

Putting this altogether, we have the following snippet. Cheers.

$(function() {
  $("#draggable").draggable();
  $("#droppable").droppable({
    drop: function(event, ui) {
      console.log(event, ui);
      alert('dropped!');
    }
  });
});

function trigger_drop() {
  var draggable = $("#draggable").draggable(),
    droppable = $("#droppable").droppable(),

    droppableOffset = droppable.offset(),
    draggableOffset = draggable.offset(),
    dx = droppableOffset.left - draggableOffset.left,
    dy = droppableOffset.top - draggableOffset.top;

  draggable.simulate("drag", {
    dx: dx,
    dy: dy
  });
}
#draggable {
  width: 100px;
  height: 100px;
  padding: 0.5em;
  float: left;
  margin: 10px 10px 10px 0;
}
#droppable {
  width: 150px;
  height: 150px;
  padding: 0.5em;
  float: left;
  margin: 10px;
}
br {
  clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>

<script src="https://rawgit.com/jquery/jquery-ui/1-11-stable/external/jquery-simulate/jquery.simulate.js"></script>


<div id="draggable" class="ui-widget-content">
  <p>Drag me to my target</p>
</div>

<div id="droppable" class="ui-widget-header">
  <p>Drop here</p>
</div>
<br>
<button onclick="trigger_drop()">trigger drop event</button>
  • If you want to fire the same functionality that happens when you actually do drop the object by mouse, you can encapsulate your drop script into a function that you then can simply call elsewhere, too.

  • If you want to have an animated motion of your item being dragged & dropped, you should .stop().animate({}) it to the target position, followed by the step above.

  • If you simply want to append it to the drop target, just .appendTo($('#yourtargetid'));.

Sorry if I missunderstood anything, my reputation points aint enough to just ask you beforehand as I'd have done everywhere else.

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