简体   繁体   English

在文档上绑定事件侦听器与在多个元素上绑定事件侦听器

[英]Binding a event listener on document vs binding event listener on multiple elements

This is kind of related to my previous Q where I had this code: http://jsfiddle.net/NQQL6/这有点与我之前的 Q 有这个代码有关: http : //jsfiddle.net/NQQL6/

There I'm attaching an event listener for dragstart and dragend on document .有我附加了一个事件侦听器dragstartdragenddocument The alternative would be:替代方案是:

var elements = document.querySelectorAll('a');

for(var i = 0; i < elements.length; i++){
  elements[i].addEventListener('dragstart', function(){
    ...
  })
}

So is there any difference?那么有什么区别吗? Should I go this way?我应该走这条路吗?

The only difference is the when drag events trigger.唯一的区别是拖动事件触发的时间。 When on the element it only triggers if the drag/drop is happening on that element, where as set for the document they are triggered when drag/drop anywhere on the page.当在元素上时,只有在该元素上发生拖/放时才会触发,根据文档设置,当在页面上的任何位置拖/放时,它们会被触发。

Unless you do some css tricks to show where the drag/drop area is the user might try to drop whatever somewhere else and the event wont ever get triggered.除非您执行一些 css 技巧来显示拖放区域的位置,否则用户可能会尝试将任何内容放在其他地方,并且该事件永远不会被触发。

It all depends on what you need happen.这一切都取决于你需要发生什么。 For instance when dealing with file drag and drop i usually put the listener on the document as if it were just on an element and the user doesnt drag the file onto that element the browser just decides to display the file navigating the user away from your page (if its a img,text,html etc file, otherwise it tries to download it).例如,在处理文件拖放时,我通常将侦听器放在文档上,就好像它只是放在一个元素上一样,而用户不会将文件拖到该元素上,浏览器只是决定显示文件,使用户远离您的页面(如果它是一个 img、text、html 等文件,否则它会尝试下载它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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