简体   繁体   English

将元素从一个div内部拖动到另一个

[英]Drag element from inside one div into another

I want to have the capability of dragging an element from inside one div into another. 我想具有将元素从一个div内拖动到另一个div的功能。

jQuery UI draggable and droppable , but they seem to only manipulate the elements visually, using position:relative without moving them through the DOM. jQuery UI的拖动投掷的 ,但它们似乎只操纵元件在视觉上,使用position:relative没有通过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例如:

<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 ? #moveMe如何从#firstDiv#secondDiv

It is not manipulating DOM because as far as I know that's what they are designed to do. 它不是在操纵DOM,因为据我所知,这就是他们的目的。

If you want to manipulate the DOM then you can the following trick 如果您想操纵DOM,则可以采取以下技巧

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 您可以使用helper选项然后在放置元素时使用THEN ,读取坐标,然后使用jQuery克隆函数将原始div#moveMe克隆到放置区域#secondDiv ,然后删除原始元素#firstDiv > div#moveMe

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. 问题是,正如您所提到的,它们是按position: relative设置的position: relative对象将要从放置位置更改位置,因为它现在将相对于新父对象。 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/ . 查看此CodePen的工作示例: http ://codepen.io/anon/pen/KfDyj/。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM