我想允许用户拖放文件进行上传。但是,我不希望他们能够拖放页面上已有的HTML图像/链接。
捕获:这些图像和链接将位于contentEditable容器中,因此禁止拖动它们是不可取的。目标是简单地防止dropzone在您上面拖动非文件时点亮。
例如:
$(function() {
$('#drop')
.on('dragover', function(event) {
event.preventDefault();
$('#drop').addClass('active');
})
.on('dragleave drop', function(event) {
event.preventDefault();
$('#drop').removeClass('active');
});
});

body {
font-family: sans-serif;
}
#drop {
border: dashed 3px #888;
padding: 20px;
}
#drop.active {
background: black;
color: white;
}
ol {
margin: 20px 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="drop">
DROP HERE
</div>
<ol>
<li>Try dragging a file from your computer over it. This is acceptable.</li>
<li>Now try dragging the image below image over it. This is not acceptable.</li>
<li><a href="#">Try dragging this link over it, too! Also not acceptable.</a></li>
</ol>
<p>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg">
</p>
<p>
The goal here is to prevent the dropzone from lighting up when you drag a non-file over it, but to not disable dragging entirely on these types of elements.
</p>
&#13;
答案 0 :(得分:0)
我正在寻找的解决方案是检查数据传输类型。如果它包含Files
,则至少有一个文件被拖放,因此我们应该激活并允许它。否则,我们可以简单地忽略拖放操作。
$('#drop')
.on('dragover', function(event) {
event.preventDefault();
// Only activate dropzone if the user is dragging a file
if( $.inArray('Files', event.originalEvent.dataTransfer.types) === -1 ) {
return;
}
$('#drop').addClass('active');
})
.on('dragleave drop', function(event) {
event.preventDefault();
// Only accept drops if the user is dropping a file
if( $.inArray('Files', event.originalEvent.dataTransfer.types) === -1 ) {
return;
}
$('#drop').removeClass('active');
});