问题
I'm using html5 dragevents in a single page application.
Currently, I'm listening to the dragleave and dragenter events to set the proper classes on the elements.
But, when two valid target elements(A and B) are next to each other, and we drag an elment through A into B, the events are fired in the following sequance.
+--------------+-------------+
| | |
+-------+ | A | B |
| | | | |
| Elem +------------------------------------> |
| | | | |
+-------+ | | |
+--------------+-------------+
dragenterof Adragenterof Bdragleaveof A
The expected order of the events would be,
dragenterof Adragleaveof Adragenterof B
I assumed that this would be the order since the item has to leave A before entering B. Am I missing something here? Is there a rationale for the dragenter being fired before the dragleave? Is there a way to change this behaviour?
I have a JSFiddle here.
The code itself is pretty simple with the dragenter and dragover being listened to.
dragenter: function(e) {
console.log("basket dragenter");
// logic here
},
dragleave: function(e) {
console.log("basket dragleave");
// logic here
},
回答1:
A little late to the party but, here is my use case. Imagine that B is entirely enclosed in A:
+---------------------------+
| A |
| +---------------+ |
+-----+ | | B | |
| | | | | |
| -|------|------|---> | |
+-----+ | | | |
| | | |
| +---------------+ |
+---------------------------+
You can leave A here by leaving it entirely, or by leaving it to go to B. The fact that B.dragenter is fired before A.dragleave allows you to be aware of the direction of the drag in the A.dragleave handler.
In fact I just realise that the same goes for your use-case: you can leave A to the void (left-up-down) or to go to B (right).
Note that the above is my interpretation of 'why' this is useful. The behaviour itself confirmed by this section of the spec:
https://www.w3.org/TR/html51/editing.html#drag-and-drop-processing-model
来源:https://stackoverflow.com/questions/43275189/html-5-drag-events-dragleave-fired-after-dragenter