jQuery.draggable() - 恢复按钮单击

时间:2012-04-04 15:22:35

标签: jquery jquery-ui-draggable revert jquery-ui-droppable

我有几个draggable&我页面上的droppable元素,其中包含accept个属性。

目前我的代码设置如下:

$(".answer." + answer).draggable({
    revert: "invalid"
    , snap: ".graph"
});
$(".graph." + graph).droppable({
    accept: ".answer." + answer
});

因此,如果答案不正确,则将其恢复到原来的位置。

用户还需要能够重置页面上的所有内容。我尝试了以下内容,但它不起作用:

$("btnReset").click(function(){
   $(".graph.A").draggable({revert:true});
});

1 个答案:

答案 0 :(得分:10)

由于没有内置方法可以满足您的需求,因此您必须自己模拟恢复行为。您可以存储每个可拖动元素的原始位置,然后在单击重置按钮时,将它们设置为回到这些位置。

这是一个简化的 jsFiddle example

jQuery的:

$("#draggable").draggable({
    revert: "invalid"
});
$("#draggable2").draggable({
    revert: "invalid"
});
$("#droppable").droppable({
});
$("#btnReset").click(function() {
    $("#draggable, #draggable2").animate({
        "left": $("#draggable").data("left"),
        "top": $("#draggable").data("top")
    });
});
$(".ui-widget-content").data("left", $(".ui-widget-content").position().left).data("top", $(".ui-widget-content").position().top);

HTML:

<div id="draggable" class="ui-widget-content">
    <p>I revert when I'm dropped</p>
</div>
<div id="draggable2" class="ui-widget-content">
    <p>I revert when I'm dropped</p>
</div>
<button id="btnReset">Reset</button>
<div id="droppable" class="ui-widget-header">
    <p>Drop me here</p>
</div>​