Drag element from inside one div into another

后端 未结 2 603
遥遥无期
遥遥无期 2021-01-27 02:36

I want to have the capability of dragging an element from inside one div into another.

jQuery UI draggable and droppable, but they seem to only manipulate the elements v

2条回答
  •  终归单人心
    2021-01-27 02:47

    The functionality is fairly trivial, but may have unpredictable results. The problem is since they are, as you mentioned set with position: relative the object is going to change position from where it is dropped since it will now become relative to the new parent. To fix this you will have to recalculate the position every time you drop the object.

    This can still be done fairly simply by finding the position of the past parent versus the new parent and the new offset.

    This whole functionality can be accomplished like so

    $(document).ready(function () {
      $( "#draggable" ).draggable();
      $( ".droppable" ).droppable({
          drop: function( event, ui ) {
            //Get the position before changing the DOM
            var p1 = ui.draggable.parent().offset();
            //Move to the new parent
            $(this).append(ui.draggable);
            //Get the postion after changing the DOM
            var p2 = ui.draggable.parent().offset();
            //Set the position relative to the change
            ui.draggable.css({
              top: parseInt(ui.draggable.css('top')) + (p1.top - p2.top),
              left: parseInt(ui.draggable.css('left')) + (p1.left - p2.left)
            });
          }
        });
    });
    

    Check out this CodePen for a working example: http://codepen.io/anon/pen/KfDyj/.

提交回复
热议问题