简体   繁体   English

如何在javascript中模拟HTML5拖放事件?

[英]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. 作为标题,我试图在javascript中模拟HTML5拖放事件。

I've looked into jquery.ui.simulate and also the simulate function here . 我查看了jquery.ui.simulate以及这里的模拟函数。 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. 两者似乎都能够通过模拟与jQuery UI对象一起使用的mousedown,mousemove和mouseup来模拟拖放。

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. 触发mousedown似乎没有触发dragstart HTML5事件。

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? 有没有办法让模拟mousedown / mousemove / etc启动dragstart事件,还是有办法直接模拟dragstart(然后删除)事件?

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 我已经尝试修改SO上模拟功能来添加HTML5 dragstart事件,所以我可以在演示页面上尝试类似下面的内容

 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. 但是我收到错误,因为我不确定如何正确地在模拟的dragstart事件上创建dataTransfer对象。

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. 基本上,我会接受任何答案,让我可以使用jquery.ui.simluate(或其他库)或使用修改版本的方法将元素'three' 拖动演示拖放页面中的'bin'元素模拟我在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. 在我的拖放文件上传库( Droplit ,无耻插件)的单元测试中,我一直在使用jQuery的Event方法。 In my source code I set my drop event listener with element.ondrop() like so: 在我的源代码中,我使用element.ondrop()设置我的drop事件监听器,如下所示:

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. 然后我可以通过构建一个假的事件对象并将其传递给ondrop方法来测试它。

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

You can try this one. 你可以尝试这个。 It uses native HTML5 events, no jQuery 它使用原生HTML5事件,没有jQuery

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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