jQuery:如何在代码中模拟拖放?

编辑:这是一个链接,向您展示我的示例代码: http : //www.singingeels.com/jqtest/

我有一个非常简单的页面,它引用了jquery-1.3.2.js,ui.core.js(最新版本)和ui.draggable.js(也是最新版本)。

我有一个div,我可以很容易地拖动(当然使用鼠标):

hello

然后在JavaScript中:

 $("#myDiv").draggable(); 

这是完美的。 但是,我需要能够仅使用代码来模拟“拖放”。 我主要使用它,但问题是触发的事件是占位符事件

如果你打开“ui.core.js”并滚动到底部…你会看到:

 // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) { }, _mouseDrag: function(event) { }, _mouseStop: function(event) { }, _mouseCapture: function(event) { return true; } 

为什么在我的模拟中没有正确地扩展事件,但是当你用鼠标点击它们时,它们是? – 关于如何强制_mouseDrag:属性服从“ui.draggable.js”中的覆盖扩展的任何想法?

解决这个问题将是巨大的 – 我计划在以后显示主要的好处。

谢谢,-Timothy

编辑:这是一个链接,向您展示我的示例代码: http : //www.singingeels.com/jqtest/

编辑2:点击上面的链接和查看源…你会看到我正在尝试做什么。 这是一个片段:

 $(document).ready(function() { var myDiv = $("#myDiv"); myDiv.draggable(); // This will set enough properties to simulate valid mouse options. $.ui.mouse.options = $.ui.mouse.defaults; var divOffset = myDiv.offset(); // This will simulate clicking down on the div - works mostly. $.ui.mouse._mouseDown({ target: myDiv, pageX: divOffset.left, pageY: divOffset.top, which: 1, preventDefault: function() { } }); }); 

在JQuery论坛中有一个关于它的问题 。 在撰写本文时尚未解决,但未来可能会有更多信息。


编辑:在论坛上回答:

我建议你使用simulate插件,这是jQuery UI用于拖放unit testing的:

https://github.com/jquery/jquery-ui/blob/master/external/jquery-simulate/jquery.simulate.js

您可以通过查看unit testing来查看使用示例

https://github.com/jquery/jquery-ui/blob/master/tests/unit/draggable/core.js

https://github.com/jquery/jquery-ui/blob/master/tests/unit/draggable/events.js

感谢rdworth。

我找到了一个效果很好的解决方案。 我有一个drop事件调用一个名为onDragAndDrop()的函数。 该函数有两个参数, draggable jQuery对象和droppable jQuery对象。

 $('.my-drop-target').droppable({ drop: function(event, ui) { onDragAndDrop(ui.draggable, $(event.target)); } }); 

在我的测试中,我有一个直接调用onDragAndDrop的函数,但确保带有鼠标的用户可以执行该操作。

  var simulateDragAndDrop = function(draggable, droppable) { if (!draggable.data('uiDraggable')) { throw new Error('Tried to drag and drop but the source element is not draggable!'); } if (!droppable.data('uiDroppable')) { throw new Error('Tried to drag and drop but the target element is not droppable!'); } onDragAndDrop(draggable, droppable); } 

我发现它是一个很好的,易于使用的unit testing解决方案。 我可能最终还会将它用于键盘可访问的后备。

您需要显示用于“模拟”此代码的代码。 我的直觉是你需要构建正确的DOM事件并解雇它们,但我不知道jQuery是否具有注入人工事件的工具。

你能直接调用事件处理程序吗?