jQuery.on("drop") 不触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19223352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery.on("drop") not firing
提问by TreacleWench
I'm trying to implement drag and dropping of files from the desktop the browser window. I have used jQuery to attach three events to the HTML element as in the code below:
我正在尝试实现从桌面浏览器窗口拖放文件。我使用 jQuery 将三个事件附加到 HTML 元素,如下面的代码所示:
$("html").on("dragover", function() {
$(this).addClass('dragging');
});
$("html").on("dragleave", function() {
$(this).removeClass('dragging');
});
$("html").on("drop", function(event) {
event.preventDefault();
event.stopPropagation();
alert("Dropped!");
});
The 'dragover' and 'dragleave' events work fine, displaying an inset border around the entire page when I drag a file over an removing it if I drag the file out again.
'dragover' 和 'dragleave' 事件工作正常,当我将文件拖过时在整个页面周围显示一个插入边框,如果我再次将文件拖出则将其删除。
However, the 'drop' event doesn't seem to fire at all, the dropped file simply opens in the browser window.
但是,'drop' 事件似乎根本没有触发,丢弃的文件只是在浏览器窗口中打开。
Does anyone have any idea why this event is not firing?
有谁知道为什么这个事件没有触发?
Btw, I am testing this in the latest version of Chrome and using jQuery 1.10.2.
顺便说一句,我正在最新版本的 Chrome 中测试这个并使用 jQuery 1.10.2。
回答by Christian Lund
You need to cancel all events
您需要取消所有活动
$("html").on("dragover", function(event) {
event.preventDefault();
event.stopPropagation();
$(this).addClass('dragging');
});
$("html").on("dragleave", function(event) {
event.preventDefault();
event.stopPropagation();
$(this).removeClass('dragging');
});
$("html").on("drop", function(event) {
event.preventDefault();
event.stopPropagation();
alert("Dropped!");
});
回答by JimmyBlu
In addition to Christian's solution this can be shortened to:
除了 Christian 的解决方案,这可以缩短为:
$('#my-dropzone')
// crucial for the 'drop' event to fire
.on('dragover', false)
.on('drop', function (e) {
// do something
return false;
});