如何在两个容器之间拖放?

时间:2017-09-07 13:36:18

标签: javascript jquery jquery-ui

运行此 HTML

<div class="container">
  <div class="row">
    <div class="col">
      <div class="row">
        <div class="col">
          <div id="container1">
            <div class="dropEL col-6">
              <p>Element 1</p>
            </div>
            <div class="dropEL col-6">
              <p>Element 2</p>
            </div>
          </div>
        </div>
        <div class="col">
          <div id="container2"></div>
        </div>
      </div>
    </div>
  </div>
</div>

JS

var currentParent;  
$(".dropEL").draggable({
  containment: "#container2",
  grid: [ 20, 40 ],
  snap: true,
  start: function(){
    currentParent = $(this).parent().attr('id');
  }
}); 
$('#container1, #container2').droppable({
  accept:'.dropEL',
  drop: function(event,ui) {
    if (currentParent != $(this).attr('id')) {
      $(ui.draggable).appendTo($(this)).removeAttr('style');
    }
    $(this).find("div").on("click", function(e){
      e.stopImmediatePropagation();
      if($(this).hasClass("col-6")) {
        $(this).find("p").css("background-color", "red");
        $(this).removeClass("col-6").addClass("col"); 
      } else {
        $(this).find("p").css("background-color", "green");
        $(this).removeClass("col").addClass("col-6");
      }
    });
  }
});

我能够从容器1拖放到容器2,但我无法拖放回容器1.我怎么能?

CodePen此处

1 个答案:

答案 0 :(得分:0)

只需更改以下代码

 $(".dropEL").draggable({
      containment: ".container",
      grid: [ 20, 40 ],
      snap: true,
      start: function(){
        currentParent = $(this).parent().attr('id');
      }
    }); 

你提到包容为#container2是根本原因。 请找到更新后的密码笔:https://codepen.io/anon/pen/wqLvQB