简体   繁体   中英

jquery drag and drop: Can I prevent an element to be dropped to another div after it has been dropped?

I have been trying to get this work for a long time and without any luck, I decided to ask here.

I am creating drag and drop divs using jquery ui library.

Currently, I have many divs with class 'parent' that I add dynamically on the page:

$( ".parent" ).droppable({
        accept: ".child",
        activeClass: "ui-state-hover",
        hoverClass: "ui-state-active",
    tolerance:'touch',
        drop: function( event, ui ) {
            $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" )
                    .html( "Dropped!" ).appendTo(ui.Target);
        }
    });

I then create a div on the fly with class 'child' and the child div can be dragged and dropped into any of the parent divs. Please note that for the parent droppables, tolerance is set to 'touch'

$( ".child" ).draggable();

Parent divs are smaller in size than the child div. Whenever I drag a child div and if I move it over two parent divs (please note that at this point, I haven't dropped the child div), ideally, I want the child div to be dropped only into the first parent div.

What happens is that the child div is appended into the first parent div. Then it is moved from the 1st parent div into the second parent div.

Is there a way to allow child div to remain draggable but only be dropped into the first parent div?

Thanks for reading.

If it is not clear, please let me know and I will rephrase it

Dragging the child over parent 2 and 3 shows the same behaviour: http://jsfiddle.net/Dyawa/3/

I notice you took the point of noting it is set to:

tolerance:'touch'

But this is exactly what this means - 'Draggable overlaps the droppable any amount.' (from http://api.jqueryui.com/droppable/#option-tolerance )

Check this out: http://jsfiddle.net/Dyawa/2/ - see the difference just by removing the tolerance.

Suggest you use:

tolerance: 'pointer'

Since I don't see the whole code it's a bit hard to guess but try the below :

$( ".parent" ).droppable({
        accept: ".child",
        activeClass: "ui-state-hover",
        hoverClass: "ui-state-active",
    tolerance:'touch',
        drop: function( event, ui ) {
            $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" )
                    .html( "Dropped!" ).appendTo(ui.Target);
                     event.preventDefault(); // or `return false;` 
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM