简体   繁体   中英

How to simulate HTML5 Drag and Drop events in javascript?

As title, I'm trying to simulate an HTML5 drag and drop event in javascript.

I've looked into jquery.ui.simulate and also the simulate function here . Both seem to be able to be used to simluate drag and drop by simulating mousedown, mousemove, and mouseup which works with jQuery UI objects.

But the drag/drop events in pages like drag and drop demo site do not seem to be simulatable using the same methods. Triggering a mousedown doesn't seem to fire the dragstart HTML5 event.

Is there a way to either get dragstart events to be fired based on a simulating mousedown/mousemove/etc, or is there a way to simulate the dragstart (and then drop) events directly?

I've tried modifying the simulation function found on SO to add the HTML5 dragstart event so I could try something like the following on the demo page

 simulate( document.querySelector('#three'), 'dragstart')

but I get an error because I'm not sure how to create the dataTransfer object on the simulated dragstart event correctly.

Basically, I'll accept any answer that would let me drag element 'three' to the 'bin' element in the demo drag and drop page either using jquery.ui.simluate (or another library) or by using a modified version of the simulate function I found on SO.

Your best bet is to recreate a fake event object.

In my unit tests for a drag-and-drop file upload library ( Droplit , shameless plug), I have been doing this with jQuery's Event method. In my source code I set my drop event listener with element.ondrop() like so:

element.ondrop = function(e) {
  e.preventDefault();
  readFiles(e.dataTransfer.files);
};

And then I can test this out by building a fake event object and passing it into the ondrop method.

element.ondrop($.Event('drop', {dataTransfer: { files: [] }}));

You can try this one. It uses native HTML5 events, no jQuery

https://github.com/Photonios/JS-DragAndDrop-Simulator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM