为什么preventDefault不起作用? [英] Why preventDefault does not work?
问题描述
这是我的代码的一部分。
如果我尝试在块上删除图像,则preventDefault不起作用。
This is a part of my code. If I try to drop an image on the block preventDefault does not work.
jQuery(document).ready(function($) {
$.event.props.push('dataTransfer');
$('#imgDropzone').on({
dragenter: function(e) {
$(this).css('background-color', '#ffd1ff');
},
dragleave: function(e) {
$(this).css('background-color', '');
},
drop: function(e) {
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0];
var fileReader = new FileReader();
var el = $(this);
fileReader.onload = (function(file) {
return function(event) {
alert(event.target.result);
};
})(file);
fileReader.readAsDataURL(file);
}
});
});
推荐答案
您需要 * 防止所有其他拖动事件的默认值:
You need* to prevent default for all the other drag events as well:
参见 http://jsfiddle.net/LrmDw/2/
$('#imgDropzone').on("dragenter dragstart dragend dragleave dragover drag drop", function (e) {
e.preventDefault();
});
解释原始jsfiddle中无效的内容:
To explain what's not working in the original jsfiddle:
当您将文件放入droparea(或页面中的任何位置)时,浏览器的默认行为是导航并尝试解释该文件。例如,如果删除普通的
txt文件,浏览器将离开jsfiddle并显示txt文件的内容。这是在Chrome中。
When you drop a file in the droparea (or anywhere in the page), the browser's default behavior is to navigate away and try to interpret the file. If you drop a normal txt file for example, the browser will navigate away from jsfiddle and display contents of the txt file. This is in Chrome.
顺便说一下,base64网址不是优选的,因为它们会复制数据。只需获取指向该文件的blob指针并使用:
Btw, base64 urls are not preferable since they duplicate data. Simply grab a blob pointer to the file and use that:
var file = e.dataTransfer.files[0];
var src = (window.URL || window.webkitURL).createObjectURL(file);
$("<img>", {src: src}).appendTo("body");
参见
我不确切知道哪些,但我从来不必关心
这篇关于为什么preventDefault不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!