如何在“drop"事件后停止重定向?

2022-01-11 00:00:00 drag-and-drop jquery html

在 Firefox 中将文件放入 div 后,网页将被重定向到该文件.我试图在 drop 处理程序中使用 jQuery 的 e.preventDefault() 来阻止这种传播,但失败了.

After dropping a file into a div in Firefox, the webpage will be redirected to this file. I tried to stop this propagation using jQuery's e.preventDefault() in drop handler, and failed.

请参阅此演示,将文件放入 #test 不会't 重定向网页,但放入 #test1 会,我想知道为什么.我是否应该始终将处理程序绑定到 dragenterdragoverdragleavedrop 以防止在 drop<之后传播/代码>?

See this demo, dropping a file into #test won't redirect the webpage, but dropping into #test1 will, I want to know why. Should I always bind handlers to dragenter, dragover, dragleave and drop to prevent propagation after drop?

更新:

我在 html5doctor 上找到了一些提示:

I found some tips on html5doctor:

要告诉浏览器我们可以放入这个元素,我们所要做的就是取消拖动事件.然而,由于 IE 的行为不同,我们需要对 dragenter 事件做同样的事情.

To tell the browser we can drop in this element, all we have to do is cancel the dragover event. However, since IE behaves differently, we need to do the same thing for the dragenter event.

和 Mozilla 声明:

And Mozilla claims:

dragenterdragover 事件的监听器用于指示有效的放置目标,即拖动项目可能的位置被丢弃.

A listener for the dragenter and dragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped.

但我在 firefox 上测试了 这个演示,#test 有效并且#test1 没有,看来 Mozilla 犯了一个错误,而 html5doctor 是对的:Firefox 只需要 dragover 才能使 drop 工作.

But I test this demo on firefox, #test works and #test1 doesn't, seems Mozilla made a mistake, and html5doctor is right: Firefox needs dragover only to make drop work.

推荐答案

ondragover 事件需要在 Google Chrome 和 Safari 中取消允许触发 ondrop 事件.

The ondragover event needs to be canceled in Google Chrome and Safari to allow firing the ondrop event.

相关文章