jQuery UI: Drop into relatively positioned container

前端 未结 2 1473
野趣味
野趣味 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

提交回复
热议问题