Why preventDefault does not work?

不问归期 提交于 2019-12-23 13:03:42

问题


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);
                }
            });
        });

http://jsfiddle.net/LrmDw/


回答1:


You need* to prevent default for all the other drag events as well:

see http://jsfiddle.net/LrmDw/2/

$('#imgDropzone').on("dragenter dragstart dragend dragleave dragover drag drop", function (e) {
    e.preventDefault();
});

To explain what's not working in the original jsfiddle:

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.


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");

See

http://jsfiddle.net/LrmDw/3/

I don't know exactly which ones but I never had to care



来源:https://stackoverflow.com/questions/14674349/why-preventdefault-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!