【发布时间】:2016-04-18 16:36:51
【问题描述】:
我正在为此寻找跨浏览器解决方案。我提前告诉你,我不想知道是否只是一个文件,因为我找到了解决方案。我想知道文件基本上是音频、图像还是视频。在 Chrome 中,当您触发 dragenter 事件时,您可以从此处获取该数据:
ev.originalEvent.dataTransfer.items[0].type;
但在 Firefox、Safari 和 IE 中,“items”规范尚未应用: https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/items
编辑:截至 2021 年底,此功能现在为 widely supported。
在那些浏览器中,您只能看到“文件”属性:
ev.originalEvent.dataTransfer.files[0];
但是在 Dragenter 上 files[0] 是空的。我该如何解决这个问题才能知道这些其他浏览器中的文件类型?
示例(仅适用于 Chrome):
$(document).on('dragenter', '.drop-zone', function(ev) {
var e = ev.originalEvent;
e.dataTransfer.dropEffect = 'copy';
var file = e.dataTransfer.items[0];
var type = file.type.slice(0, file.type.indexOf('/'));
$(ev.target).html(type);
});
$(document).on('dragleave', '.drop-zone', function(ev) {
$(ev.target).html('Drag your file over here to know the type, no need to drop it');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drop-zone">Drag your file over here to know the type, no need to drop it</div>
【问题讨论】:
-
试过
input type="file"?
标签: javascript html drag-and-drop cross-browser