问题
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 div
s 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