javascript HTML5 拖放 getData() 仅适用于 Chrome 中的放置事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9534677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 Drag and Drop getData() only works on drop event in Chrome?
提问by Chris Pearce
I'm currently working on a project at work using the HTML5 Drag and Drop API to provide added functionality including dragging items in and out of browsers. I am currently coming across issues which are specific to Chrome (otherwise only tested in Firefox, which works as expected).
我目前正在使用 HTML5 拖放 API 处理一个项目,以提供附加功能,包括将项目拖入和拖出浏览器。我目前遇到了 Chrome 特有的问题(否则只能在 Firefox 中测试,它按预期工作)。
The issue is that I cannot use the event.dataTransfer.getData(type)
method to return the data set on the dragstart
event in any events except the drop
event.
问题是我不能使用该event.dataTransfer.getData(type)
方法dragstart
在除事件之外的任何事件中返回事件的数据集drop
。
I set the event like so, after binding to the dragstart
event (which DOES fire):
在绑定到dragstart
事件(确实触发)之后,我像这样设置事件:
event.dataTransfer.setData('text/plain', "some string")
Then in the drop
event, I can get the data fine.
然后在drop
事件中,我可以很好地获取数据。
event.dataTransfer.getData('text/plain')
However I cannot use the same method as above on any other events (such as dragover
). Even if I try and use the above method on the line after calling setData()
(i.e., in the dragstart
callback), then it will still return undefined
.
但是,我不能对任何其他事件(例如dragover
)使用与上述相同的方法。即使我在调用后setData()
(即在dragstart
回调中)尝试并在行上使用上述方法,那么它仍然会返回undefined
.
So, in Chrome, the issue is that getData
in Chrome will always return undefined
, except within the drop
event callback. (In Firefox, I can successfully get the correct data.)
因此,在 Chrome 中,问题在于getData
Chrome 中将始终 return undefined
,除非在drop
事件回调中。(在 Firefox 中,我可以成功获取正确的数据。)
If you have the reference to the dataTransfer
object of the same dragging element, then why should you not be able to get the data until it is dropped?
如果你有对dataTransfer
同一个拖动元素的对象的引用,那为什么你不能在拖放之前获取数据呢?
Just wondering:
就是想:
- Has anyone had this trouble with Chrome before?
- What workarounds are there?
- Or, is it something Chrome needs to fix?
- 以前有人在 Chrome 上遇到过这个问题吗?
- 有哪些解决方法?
- 或者,Chrome 需要修复什么?
Resources: Specification for HTML5 drag and drop.
资源: HTML5 拖放规范。
采纳答案by robertc
WebKit, and hence Chrome, is quite restrictive on when you can call getData
. You're not allowed to do it inside dragstart
or dragover
. I think this is the canonical bug.
WebKit 以及 Chrome 对何时可以调用getData
. 你不能在里面dragstart
或dragover
. 我认为这是规范错误。
回答by Z. Khullah
Referencing this answer:
参考这个答案:
The data is only available on drop, this is a security feature since a website could grab data when you happen to be dragging something across the webpage.
数据仅在放置时可用,这是一项安全功能,因为当您碰巧在网页上拖动某些内容时,网站可能会抓取数据。