سؤال

I have a JQuery droppable which contains a number of dynamically created child elements. I need to react to drops of other elements into the droppable, but only drops directly into this element, and not into one of the children.

My question is: how can I determine that the drop did not happen on top of one of the children? event.target holds always the droppable, even if the drop occured on a child. I have seen solutions where mouseenter and mouseleave events are registered for the children, which alter some state variable that is read in the drop function, but I do not want to use this solution.

Is there any better way to determine inside the drop function the actual element the drops happened on? Or is there somehow a way to configure that the drop event should not fire when the drop happens on children?

هل كانت مفيدة؟

المحلول

I found an acceptable solution. It is based on the mouse position information that you can get from ui.helper.

At first, this solution was not working for me because, at least in my specific case, sometimes the drag helper itself was returned by document.elementFromPoint(). The solution that made this approach working was to temporarily hide the helper. This is not a clean solution but I do not see a better one.

$(dropElement).droppable({
    drop: function(event, ui) {
        var mouseXPosition = ui.helper.position().left,
            mouseYPosition = ui.helper.position().top;

        $(ui.helper).hide();
        var targetElement = document.elementFromPoint(mouseXPosition, mouseYPosition);
        $(ui.helper).show();

        if (targetElement.id === $(dropElement).attr('id')) {
            // do your drop logic here
        }           
    }
});

As a side node, the mentioned solution based on mouseleave did not work for me, because the children of the droppable contain themself draggable elements that can be dropped into the droppable, and in this case if something is dragged out of an element with a mouseleave event handler registered, mouseleave is not fired. But using event handlers for such functionalities should be avoided anyway.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top