Drag element from inside one div into another

北城余情 提交于 2019-12-11 09:21:18

问题


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 visually, using position:relative without moving them through the DOM. If they can, I can't seem to find an example or figure out how.

Say if I have two simple divs such as:

<div id="firstDiv">
    <div id="moveMe">I need to be moved to secondDiv</div>
</div>
<div id="secondDiv">
</div>

how can #moveMe be dragged and dropped from #firstDiv into #secondDiv?


回答1:


It is not manipulating DOM because as far as I know that's what they are designed to do.

If you want to manipulate the DOM then you can the following trick

You can use helper option, THEN when the element is dropped, read the co-ordinates and then use jQuery Clone function to clone your original div#moveMe to the drop area #secondDiv AND THEN remove the original element #firstDiv > div#moveMe




回答2:


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/.



来源:https://stackoverflow.com/questions/22799779/drag-element-from-inside-one-div-into-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!