4

What I'm trying to do is to swap elements in different div elements. Here is my code: JSfiddle

Each div can have only one dropped element. If drop_ div has dropped element and droppable element is dropped from #tire_deck it has to be refused. If element is dropped from other div it has to be swapped. Can anybody help me to achieve that?

4

2 回答 2

2

我要做的方式是在拖动开始时存储可拖动的父级,然后我们来确定我是要交换孩子还是停止事情。

这是小提琴:

http://jsfiddle.net/vvn5S/

和javascript:

        $(function () {
            var origin;
            $(".tire").draggable({
                appendTo: "body",
                cursor: "move",
                helper: 'clone',
                revert: "invalid",
                start: function (event, ui) {
                    origin = event.target.parentNode;
                }
            });
            $("#tire_deck").droppable({
                tolerance: "intersect",
                accept: ".tire",
                activeClass: "ui-state-default",
                hoverClass: "ui-state-hover",
                drop: function (event, ui) {
                    $("#tire_deck").append($(ui.draggable));
                }
            });
            $(".drop_1, .drop_2, .drop_3, .drop_4, .drop_5, .drop_6").droppable({
                tolerance: "intersect",
                accept: ".tire",
                drop: function (event, ui) {
                    if (this.children.length == 0) {
                        $(this).append($(ui.draggable));
                    } else {
                        if (origin.id !== "tire_deck") {
                            event.stopPropagation();
                            var copyNode = $(this).children().detach();
                            $(this).append($(ui.draggable));
                            $(origin).append(copyNode);
                        } else {
                            alert("Stopped!");
                        }
                    }
                }
            });
        });
于 2013-04-29T14:36:22.517 回答
0

我想出了如何获得我想要的结果:JSFiddle,也许它对某人有用。

在可拖动事件中,我添加start事件以获取它的原始父 ID:

            var parent_div_data;                        
            $(".tire").draggable({
                appendTo: "body",
                cursor: "move",
                helper: 'clone',
                revert: "invalid",
                start: function( event, ui ) {
                    parent_div_data = $(this).parent().attr("id");
                }
            });

然后在 droppabledrop事件中,我检查了它有多少个可拖动元素,并将第一个元素附加到第二个元素的父元素div

if($(this).find(".tire").length == 1){
                    var first = $(this).find(':first-child');
                    $('#' + parent_div_data).append(first);
                }
于 2013-04-29T13:54:11.027 回答