jQuery: How Do I simulate Drag and Drop in Code?

前端 未结 2 1517
失恋的感觉
失恋的感觉 2021-01-30 23:22

EDIT: Here\'s a link to show you my sample code: http://www.singingeels.com/jqtest/

I have a very simple page that references jquery-1.3.2.js, ui.core.js (latest version

相关标签:
2条回答
  • 2021-01-30 23:56

    I found a solution that works pretty well. I have the drop event call a function called onDragAndDrop(). That function takes two arguments, the draggable jQuery object and the droppable jQuery object.

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

    In my tests, I have a function that calls onDragAndDrop directly, but makes sure that a user with a mouse could have performed that action.

        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);
        }
    

    I've found it to be a nice, easy-to-use solution for unit tests. I'll probably end up using it for a keyboard-accessible fallback as well.

    0 讨论(0)
  • 2021-01-31 00:05

    There's a question in the JQuery forum about it. It's not resolved at the time of writing, but may have more information in the future.


    EDIT: It was answered on the forum:

    I recommend you use the simulate plugin which is what jQuery UI uses for unit testing drag and drop:

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

    You can see examples of use by looking at the unit tests

    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

    Thanks to rdworth for that.

    0 讨论(0)
提交回复
热议问题