如何将droppable仅丢弃在jquery ui中的draggable元素中

时间:2013-11-07 16:25:43

标签: javascript jquery jquery-ui

阅读一些类似的文章/问题,但如果droppables是具有相同命名类的许多元素,则无法使其正常工作。

如何使拖动的元素只被放入droppable元素中。如果将其拖到其他位置,它会返回原始父级。 (不会被拖累)。

JSFiddle Sample

HTML

<div  class="box-body">
    <div class="task">task</div>
</div>
<div class="box-body"></div>

JS

$('.task').draggable();
    $('.box-body').droppable({
        drop:function(e, ui) {
            $(e.target).append($(ui.draggable).detach().css({'top':'', 'left':''}));
    }
});

CSS

.box-body {
    height:100px;
    width:100px;
    border:1px solid #333;
}
.task {
    width:100%;
    margin:5px;
    border:1px solid #333;
}

1 个答案:

答案 0 :(得分:7)

<强>示例

这里显示如何恢复droppables的位置
http://jqueryui.com/droppable/#revert

您可以通过初始化这样的可拖动来执行此操作:$( "#draggable" ).draggable({ revert: "invalid" });

<强> JS

  $(function() {
    $( "#draggable" ).draggable({ revert: "valid" });
    $( "#draggable2" ).draggable({ revert: "invalid" });

    $( "#droppable" ).droppable({
      activeClass: "ui-state-hover",
      hoverClass: "ui-state-active",
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
      }
    });
  });

<强> 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 not dropped</p>
</div>

<div id="droppable" class="ui-widget-header">
  <p>Drop me here</p>
</div>

<强> CSS

#draggable, #draggable2 {
    width: 100px;
    height: 100px;
    padding: 0.5em;
    float: left;
    margin: 10px 10px 10px 0;
}
#droppable {
    width: 150px;
    height: 150px;
    padding: 0.5em;
    float: left;
    margin: 10px;
}