gpt4 book ai didi

HTML5 原生 Drag 'n' Drop - 检测取消

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:37 28 4
gpt4 key购买 nike

我需要在浏览器窗口之间实现 HTML 元素的拖放。

当一个元素从窗口 A 掉落到窗口 B 时,它必须从窗口 A 中移除(并添加到窗口 B)。

当拖放被取消时(发生在用户按下“esc”键时,或者有时拖放功能似乎有问题时),元素必须返回到其原始位置。

目前我正在做的是保留一个“hasBeenDropped”标志,它在 dragstart 中设置为 false,在 drop 中设置为 true。在 dragend 中,我检查了我的标志,如果它没有设置为 true,则意味着 drop 已在另一个窗口中触发,或者操作已被取消。我需要区分这两种情况(放入另一个窗口与取消),以便采取相应的行动(例如删除窗口或将其替换到原来的位置)。

TL;DR:我需要能够检测到原生 HTML5 拖放操作何时被取消(例如,当用户按下“esc”键时)。

有什么办法吗??

最佳答案

和你一样,我使用了一个标志来确定是否在其他地方成功发生了掉落,这或多或少意味着它没有被取消。然而,似乎有一种更合适的方法,如 MDN 中所述:

Finishing a Drag

Once the drag is complete, a dragend event is fired at the source of the drag (the same element that received the dragstart event). This event will fire if the drag was successful[1] or if it was cancelled. However, you can use the dropEffect property to determine what drop operation occurred.

If the dropEffect property has the value none during a dragend, then the drag was cancelled. Otherwise, the effect specifies which operation was performed. The source can use this information after a move operation to remove the dragged item from the old location. The mozUserCancelled property will be set to true if the user cancelled the drag (by pressing Escape), and false if the drag was cancelled for other reasons such as an invalid drop target, or if it was successful.

mozilla 特定的属性显然是不可取的,但 dropEffect 属性本身应该足以满足大多数目的。我自己对其进行了测试(将图 block 拖入 iframe 中的放置区)并且它似乎按预期工作。

这直接取自当前主题的 MDN 页面:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#dragend

自从您换了工作后可能对您没那么有用,但是很难找到关于这个主题的信息,所以希望下一个搜索的人会受益。

关于HTML5 原生 Drag 'n' Drop - 检测取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33630771/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com