简体   繁体   中英

'drop' event already done stopPropagation() and preventDefault() in div, why browser opens the picture after I drop it?

I am practicing writing a file drop & upload plugin. In the 400px * 400px div, where catches the 'drop' event, I've already added this code in the handler:

DropUpload.prototype.drop = function (event) {
...
        event.stopPropagation();
        event.preventDefault();
...
}

But when I drop a picture file in the div, the browser just open the picture on this page, flushing out the previous script page. I learned by googling that

      $(document).on('dragenter', function (e) 
            { e.stopPropagation(); e.preventDefault(); });
      $(document).on('dragover', function (e) 
        { e.stopPropagation(); e.preventDefault(); });
      $(document).on('drop', function (e) 
        { e.stopPropagation(); e.preventDefault(); });

can prevent opening the picture. But I think I've already prevent the drop event bubbling up in the div element by adding stopPropogation() , why should I do it again on the document element?

Is it because the drop event enters document first and then reaches div? Please help me understand this.

I am answering my own question since I made a mistake. I hope I can save you some time by sharing my mistake.

In order let drop zone handle the drop event, you have to do

event.stopPropagation();
event.preventDefault();

for all 3

    this.$element.on('dragenter', this.dragenter);
    this.$element.on('dragover', this.dragover);
    this.$element.on('drop', this.drop);

events. If you miss any one function for any one of the 3 events, the new drop will cause the browser to load the file that you just drop.

Or you can disable the default event behavior on document element, but doing it on drop zone is more logical and looks less like a hack.

This MDN document explain some details.

Sincerely,

Nick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM