[英]Prevent HTML elements from being dragged/dropped
I want to allow users to drag and drop a file for uploading. 我想允许用户拖放文件进行上传。 However, I do not want them to be able to drag and drop HTML images/links that are already on the page.
但是,我不希望他们能够拖放页面上已经存在的HTML图像/链接。
The catch: these images and links will be in a contentEditable container, so disabling dragging on them isn't desirable. 要注意的是:这些图像和链接将位于contentEditable容器中,因此不希望在其上禁用拖动。 The goal is to simply prevent the dropzone from lighting up when you drag a non-file over it.
目的是仅在将非文件拖动到拖放区上时,防止该拖放区亮起。
For example: 例如:
$(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>
The solution I was looking for is to check for the data transfer type. 我一直在寻找的解决方案是检查数据传输类型。 If it contains
Files
, there is at least one file being dragged/dropped so we should activate and allow it. 如果其中包含
Files
,则至少要拖放一个文件,因此我们应该激活并允许它。 Otherwise, we can simply ignore the drag/drop actions. 否则,我们可以简单地忽略拖放操作。
$('#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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.