我正在使用自定义帮助程序方法,该方法返回一个<div>,在删除该<div>时将其添加多次。请查看代码以更好地理解它

var dropHelp = true;


$(".product").draggable({
revert: 'invalid',
cursorAt: { top: -12, left: -20 },
 connectToSortable: ".droppable",
helper: function(event) {
  return $('<div class="helper">Helper</div>');
}
});
$(".droppable").sortable({
  placeholder: "ui-state-highlight"
}).disableSelection();
$(".droppable").droppable({
drop: function(event, ui) {
    if(dropHelp){
       //clone and remove positioning from the helper element
       var newDiv = $(ui.helper).clone(false)
           .removeClass('ui-draggable-dragging')
           .css({position:'relative', left:0, top:0});
       $(this).append(newDiv);

    //drop the draggable source element
    } else {
       $(this).append(ui.draggable);
    }
 }
 });

$('#dropDrag').click(function(){
dropHelp = !dropHelp;
});


这是HTML

<button id="dropDrag">Toggle drop "Helper" or "Draggable"</button><br/><br/><br/>

<div class="product">Product 1</div>
<div class="product">Product 2</div>
<div class="product">Product 3</div>

<div class="droppable">Drop Target</div>


完整代码可在here中找到。

我发现如果我们以可拖动的方式删除connectToSortable属性,它将正常工作。但是我需要该属性,并且当设置connectToSortable时,我没有得到为什么它具有这种性能的原因。

最佳答案

您的drop()被调用两次,因为connectToSortable也会触发drop()
(Sortable已经是可放置的)

我已编辑您的代码,以使用receive的sortable函数获得相同的结果

DEMO

var dropHelp = true;


  $(".product").draggable({
    revert: 'invalid',
    cursorAt: { top: -12, left: -20 },
     connectToSortable: ".droppable",
    helper: function(event) {
      return $('<div class="helper">Helper</div>');
    },
      stop: function(){
        $(this).css({opacity:1});
    },
       start: function(){
        $(this).css({opacity:0});
    },
  });
  $(".droppable").sortable({
      placeholder: "ui-state-highlight",
      receive: function(event, ui) {
          if(dropHelp){
           //clone and remove positioning from the helper element
           var newDiv = $(ui.helper).clone(false)
               .removeClass('ui-draggable-dragging')
               .css({position:'relative', left:0, top:0});
           $(this).append(newDiv);

        //drop the draggable source element
        } else {
           $(this).append(ui.draggable);
        }

  }
  }).disableSelection();


$('#dropDrag').click(function(){
    dropHelp = !dropHelp;
});

07-26 00:30