HTML5 Drag & Drop : How to remove class added in d

2019-09-17 21:25发布

问题:

I Have div included in another parent div that are both allowed for "drop".
In the example a class named "red" is added to all droppable object in dragenter event. So if I enter the mouse durring drag in child element both child and parent will get "red" class.

When I abort the drag&drop or if I leave elements during operation, the dragleave event will remove the added "red" class.

The problem is when I drop the element into child there are two options :

  • Option 1 : event.stopPropagation() is included in drop event
    The problem is that in this case, the parent won't execute the drop event and the "red" class will not be removed at all in parent.
  • Option 2: event.stopPropagation() is not included in drop event
    The problem is that in this case the drop event will be executed for both child and parent element. But the drop action should be done only for child element.

    I thought about a solution using stopPropagation() by runing through event.path array for removing the added class but there are probably another ways to solve the problem.

    Here the fiddler for option 1 with stopPropagation()
    Here the fiddler for option 2 without stopPropagation()

  • 回答1:

    Register a dragend event on the element that you are dragging. The dragend event is fired when you release the element that is being dragged. The event will be fired regardless of whether it was dropped in a dropzone or not. This way you can separate the drop event from the end of drag. You can filter your process using conditions.