如何在javascript中模拟HTML5拖放事件? [英] How to simulate HTML5 Drag and Drop events in javascript?

查看:97
本文介绍了如何在javascript中模拟HTML5拖放事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题,我正在尝试在javascript中模拟HTML5拖放事件。

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

我查看了jquery.ui.simulate以及模拟功能此处。两者似乎都可以通过模拟与jQuery UI对象一起使用的mousedown,mousemove和mouseup来模拟拖放。

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.

但拖放事件在像拖放演示网站这样的网页似乎无法使用相同的方法进行模拟。触发mousedown似乎没有触发dragstart HTML5事件。

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 / mousemove / etc来触发dragstart事件,或者有没有办法直接模拟dragstart(然后删除)事件?

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?

我尝试修改在SO上找到的模拟功能,以添加HTML5 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

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

但是我收到错误,因为我不确定如何正确地在模拟的dragstart事件上创建dataTransfer对象。

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

基本上,我会接受任何答案,让我将元素'three'拖到使用jquery.ui.simluate(或其他库)或使用 stackoverflow.com/questions/6157929/how-to-simulate-mouse-click-using-javascript\">模仿我在SO上找到的功能

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.

在我的拖放文件上传库的单元测试中( Droplit ,无耻的插件),我一直在使用jQuery的事件方法。在我的源代码中,我使用 element.ondrop()设置我的drop事件监听器,如下所示:

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

然后我可以通过构建一个假的事件对象并将其传递到<$ c来测试它$ c> ondrop 方法。

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: [] }}));

这篇关于如何在javascript中模拟HTML5拖放事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆