Check if droppable already contains another dragga

2019-07-21 11:57发布

问题:

I have a droppable div element that fades out when a draggable element is dragged off it. This works fine using the out event. The problem I'm getting is when there are two draggable elements on the droppable. The droppable element will still fade when I drag one off. How can I check if there is already another draggable element on the droppable so I can cancel the fade effect. I want the droppable element to fade only when the last draggable element is taken off.

$(".droppable-element").droppable({
    tolerance: 'touch',
    out:function(event,ui){

       /*Need to first check if there is another draggable element in the droppable before fading out.*/
            $(this).fadeOut('slow', function(){
                // Animation complete.

             });                
 }
});

回答1:

Are the draggable elements children (descendants) of the droppable? And are they removed from it when when they are dragged off? In that case, you could do something like this:

if ( $(this).find(".draggable-element").length == 0 )
    $(this).fadeOut('slow', function(){

Update: if I understand correctly, you dragged an element to the droppable (maybe dropped it?), then dragged another one, and removed it. In that case, you could keep track of which (or at least how many) draggables went over your droppable but didn't went out.

$(".droppable-element").droppable({
    tolerance: 'touch',
    over:function(event,ui) {
        var howMany = $(this).data("howMany") || 0;
        $(this).data("howMany", howMany+1);
    },
    out:function(event,ui){
        var howMany = $(this).data("howMany") || 1;
        $(this).data("howMany", howMany-1);
        if ( howMany == 1 )
            $(this).fadeOut('slow', function(){
                // Animation complete.
            });
    }
});