简体   繁体   English

如何将div拖放到另一个div中,并使整个元素跟随?

[英]How to drag and drop a div inside another div and make that the whole element follow?

Trying to use jqueryUI. 尝试使用jqueryUI。 I have a list with components that i want to drop inside a gridsystem. 我有一个列表,其中包含要放入网格系统中的组件。 Like a desiger thing. 像是设计的东西。 I have a div that has 我有一个div

$( "#Component1" ).draggable();

And I drop the div above in this div: 然后将div放到该div上方:

$( "#GridDiv" ).droppable({
    accept: "#component1"
});

The result I want is, when I drop the component1 div insde the GridDiv 我想要的结果是,当我将component1 div插入GridDiv

<div id="#GridDiv">
   <div id="#Component1"></div>
</div>

Is there a method for this ? 有办法吗? i cant find it.. 我找不到它..

You have to move the element by yourself after drop event : drop事件之后,您必须自己移动元素:

$( "#GridDiv" ).droppable({
    accept: "#Component1",
    drop: function( event, ui ) {
       var droppable = $(this);
       var draggable = ui.draggable;
       // Move draggable into droppable
       draggable.appendTo(droppable);
    }
});

PS: You don't need to use # in the ID field: PS:您不需要在ID字段中使用#:

<div id="GridDiv">
   <div id="Component1"></div>
</div>

Here is a working example 这是一个有效的例子

As there is a issue with the styling of the dragged element while appending to another div (see here for further information), here is another approach for you: 由于在附加到另一个div时被拖动元素的样式存在问题(请参见此处以获取更多信息),这是适合您的另一种方法:

$('#GridDiv').droppable({
    accept: "#Component1",
    drop: function (event, ui) {
        var draggable = ui.draggable;
        var offset = draggable.offset();
        draggable.appendTo( this ).offset( offset );
    }
});

Demo 演示

The following demo is slightly different: it removes the original dragged element, so the dragging functionality gets lost: 以下演示略有不同:删除了原始的拖动元素,因此拖动功能丢失了:

$('#GridDiv').droppable({
    accept: "#Component1",
    drop: function (event, ui) {
        var draggable = ui.draggable;
        var offset = draggable.offset();
        draggable.remove().appendTo( this ).offset( offset );
    }
});

Demo 2 演示2

For resizing the draggable after it is dropped you can use: 要在拖放后调整大小,可以使用:

draggable.resizable();

Demo 3 演示3

Reference 参考

.offset() .offset()

.appendTo() .appendTo()

.droppable() - drop-option .droppable()-删除选项

.remove() 。去掉()

The above all are not a correct and exact answer because the all the outputs are placed top of the window, eg, the object placed in top:0px and left:0px position. 上面所有这些都不是正确正确的答案,因为所有输出都放置在窗口的顶部,例如,对象放置在top:0px和left:0px的位置。 Try below 试试下面

var droppable = $(this);
var draggable = ui.draggable;
ui.draggable.position({ of: $(this), my: 'left top', at: 'left top' });

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

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