24

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

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

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

<div id="myDiv">hello</div>

然后在 JavaScript 中:

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

这是完美的工作。但是,我需要能够单独使用代码来模拟“拖放”。我大部分时间都在工作,但问题是正在触发的事件是占位符 events

如果你打开“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”中的覆盖扩展的任何想法?

解决这个问题将是巨大的——我计划稍后展示主要的好处。

谢谢,-蒂莫西

编辑:这是一个向您展示我的示例代码的链接: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() { }
    });
});
4

2 回答 2

30

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


编辑:在论坛上得到了回答:

我建议您使用 jQuery UI 用于单元测试拖放的模拟插件:

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

您可以通过查看单元测试来查看使用示例

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。

于 2011-01-05T15:26:37.603 回答
3

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

$('.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);
    }

我发现它是一个很好的、易于使用的单元测试解决方案。我可能最终也会将它用于键盘可访问的后备。

于 2015-10-02T22:21:00.223 回答