jQuery UI: Drop into relatively positioned container

前端 未结 2 1439
野趣味
野趣味 2021-01-25 07:30

I am using jQuery UI to drag a clone of an object onto a droppable space. However, I need the droppable space to have the position: relative property because the dr

相关标签:
2条回答
  • 2021-01-25 07:45

    try this

    $(".canvas").droppable({
        accept: '.to_drag',
        drop: function(event, ui) {
            var clone = $(ui.helper).clone();
            var parent = $('.canvas.ui-droppable');
    
            $(this).append(clone);
            var leftAdjust = clone.position().left - parent.offset().left;
            var topAdjust = clone.position().top - parent.offset().top;
            clone.css({left: leftAdjust, top: topAdjust});
    
        }
    });
    

    basically the idea is that when you enclose the droppable inside a div that is relative.. any element enclosed within droppable gets the offset position of the parent unnecessarily added to it.. so you simply remove the extra offset at the drop call back function.

    Please pay close attention to difference between .offset() and .position().. that is key to understanding the above code.

    note: I tried using jsfiddle.. but jsfiddle fiddles a bit with the positioning.. try it on your browser alone and it should work

    0 讨论(0)
  • 2021-01-25 08:05

    Here is a solution but I'm not sure, if it is that, what you're looking for.

    Replace this line:

    $(this).append($(ui.helper).clone());
    

    with this one:

    $('<div class="to_drag"></div>').appendTo(this);
    

    If you don't use the ui.helper it works.

    0 讨论(0)
提交回复
热议问题