2

阅读一些类似的文章/问题,但如果 droppables 是许多具有相同命名类的元素,则无法进行此操作。

如何使拖动的元素仅被放置在可放置的元素中。如果它被拖到其他地方,它会回到原来的父级。(不会被拖)。

JSFiddle 示例

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;
}
4

1 回答 1

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;
}
于 2013-11-07T16:34:50.057 回答