如何检测文件被拖动而不是我的页面上的可拖动元素? [英] How do I detect a file is being dragged rather than a draggable element on my page?
问题描述
我使用html5事件来启用文件和元素的拖放。我已经将dragover事件附加到正文,并且正在使用事件委派来显示可以删除draggable的位置。我的问题是如何判断一个文件是否被拖动与一个具有draggable = true的元素。我知道我可以检测通过e.target拖动的元素。但是,如何判断是否是一个文件。
I'm using the html5 events to enable both file and element drag-and-drop. I've attached the dragover event to the body and am using event delegations to show where a draggable can be dropped. My question is how can I tell if a file is being dragged vs. an element with draggable=true. I know I can detect the element being dragged via e.target. But, how can I tell if it is a file.
jquery可用。
另外,不是谈论jquery-ui draggable这里。
Also, not talking about jquery-ui draggable here.
我开始认为也许唯一的方法来检测文件将被排除和检测元素代替。如果我们没有拖动一个元素,假设它是一个文件。这将需要额外的工作,因为图像和链接可以默认拖动,所以我必须添加事件或阻止它们拖动。
I'm starting to think maybe the only way to detect the file will be by exclusion and detecting the elements instead. If we're not dragging an element, assume it's a file. This will require extra work though as images and links are draggable by default, so I will have to add events to them or prevent them from dragging.
推荐答案
您可以通过检查 dataTransfer.types
来检测要拖动的内容。这种行为在浏览器之间并不一致,所以你必须检查是否存在'Files'
(Chrome)和'application / x- moz-file'
(Firefox)。
You can detect what is being dragged by inspecting dataTransfer.types
. This behaviour is not (yet) consistent across browsers so you have to check for the existence of 'Files'
(Chrome) and 'application/x-moz-file'
(Firefox).
// Show the dropzone when dragging files (not folders or page
// elements). The dropzone is hidden after a timer to prevent
// flickering to occur as `dragleave` is fired constantly.
var dragTimer;
$(document).on('dragover', function(e) {
var dt = e.originalEvent.dataTransfer;
if (dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('Files'))) {
$("#dropzone").show();
window.clearTimeout(dragTimer);
}
});
$(document).on('dragleave', function(e) {
dragTimer = window.setTimeout(function() {
$("#dropzone").hide();
}, 25);
});
这篇关于如何检测文件被拖动而不是我的页面上的可拖动元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!