jQuery UI仅在特殊区域中删除元素

时间:2011-01-01 17:42:32

标签: javascript jquery jquery-ui

我遇到了jQuery UI的拖放问题。我动态创建新元素,这些元素放在屏幕上的四个区域之一。这些元素是可拖动的,我可以将它们放在屏幕上。但我希望这些元素只能放在三个区域之一上。

我在这里创建了一个完整的工作示例:http://jsbin.com/enusu4/

通过单击红色边框区域中的文本,将创建一个新元素并将其放置在绿色区域drop1中。此元素现在只能放置到其中一个绿色区域(drop1drop2drop3),而不是其他任何地方。我怎么能这样做?

最诚挚的问候,蒂姆。

2 个答案:

答案 0 :(得分:3)

我已经回答了类似的问题here,经过一些修改可以做你想做的事情:
Javascript:

$(function() {
    $('.drag').draggable({
        revert: "invalid",
        scope: "items"
    });
    $('#droppable').droppable({
        scope: "items",
        // if you want to disable the dragging after drop un-comment this
/*
        drop: function(e, ui) {
            $(ui.draggable).draggable({"disabled":true});
        }
        */
    });
    $('#droppable2').droppable();
    $(':button').click(function() {
        var $box = $('<div class="drag">Drag me</div>');
        $('#cont').append($box);
        $box.draggable({
            revert: "invalid",
            scope: "items"
        });
    });
});

HTML:

<div><button type="button">Add box</button></div>
<div id="droppable">Drop here</div>
<div id="droppable2">Out of scope!</div>
<div class="clear"></div>
<div id="cont">
    <div id="draggable" class="drag">Drag me</div>
    <div id="draggable2" class="drag">Drag me</div>
</div>

Example Link

编辑: 好的,这是一个更新:
Javascript:

$(function() {
    var dragOptions = {
        revert: "invalid",
        scope: "items",
        helper: "clone"
    }
    $('.drag').draggable(dragOptions);
    $('.droppable').droppable({
        scope: "items",
        drop: function(e, ui) {
            var $drop = $(this);
            $(ui.draggable).draggable({
                "disabled": true
            }).appendTo($drop);
        }

    });
    $('#droppable2').droppable();

    $(':button').click(function() {
        var $box = $('<div class="drag">Drag me</div>');
        $('#cont').append($box);
        $box.draggable(dragOptions);
    });
});

HTML:

<div><button type="button">Add box</button></div>
<div style="float: left;"><h3>Drop here:</h3>
    <div class="drop1 droppable"></div>
</div>
<div style="float: left;"><h3>Drop here:</h3>
    <div class="drop2 droppable"></div>
</div>
<div style="float: left;"><h3>Out of scope!</h3>
    <div id="droppable2"></div>
</div>
<div class="clear"></div>
<div id="cont">
    <div class="drag">Drag me</div>
    <div class="drag">Drag me</div>
</div>

Example Link 2

答案 1 :(得分:0)

$("#dropable").droppable({
   hoverClass: "ui-state-hover",
   drop: function (event, ui) {
       if ( $('.ui-state-hover').size() > 0){return false;}
       //TODO
   }
}