简体   繁体   中英

What propagation I'm stopping in drag and drop?

Following the MDN guide Selecting files using drag and drop , the code is:

var dropbox;

dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);

function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();
}

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}

function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  var dt = e.dataTransfer;
  var files = dt.files;

  handleFiles(files);
}

I understand that I've to use preventDefault() to avoid the browser from open the file that I drop. But why do I've to use stopPropagation() ? What bubbling/capturing am I stopping here?

It means 'if there any elements in the DOM containing your "dropbox" id element with matching named event handler functions attached, then they are not notified about the event'.

There is a good example at the Mozilla javascript documentation on the DOM

which has an html table containing a table data cell, both of which have an event handler attached. If you remove the ev.stopPropogation() (at line 17), both event handler functions would be called, with it there, only the table cell event handler is called.

--

There is also a similar SO question at What's the difference between event.stopPropagation and event.preventDefault?

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