3

我想讓一些圖像儘可能多地落入目標區域。但是圖像只有一次下降。我的jQuery UI代碼:在使用jQuery UI放入目標區域後克隆可拖動

$(function() { 
    $(".draggable img").draggable({ 
     revert: "invalid", 
     appendTo: "#droppable", 
     helper: "clone" 
    }); 
    $("#droppable").droppable({ 
     activeClass: "ui-state-default", 
     hoverClass: "ui-state-hover", 
     drop: function(event, ui) { 
      $(this).find(".placeholder").remove(); 
      var image = $(".ui-draggable"); 
      $("<img />").image.src.appendTo(this); 
     } 
    }); 
}); 

請看這裏演示:jsFiddle example

從你看到的圖像在div區域僅在第一次下降的例子。但我希望用戶能夠在目標區域中將拖放到的次數。

因此,例如,用戶可以拖放圖像5次,並且將在目標區域中存在5張圖像克隆的。我怎樣才能做到這一點?

回答

3

你幾乎在那裏。你確實需要helper: "clone"屬性。最好的辦法是創建一個新的克隆,當丟失事件使用.clone()激發。然後,只需初始化它,你就大功告成了:

$(function() { 
    $(".draggable img").draggable({ 
     revert: "invalid", 
     helper: "clone" 
    }); 
    $("#droppable").droppable({ 
     activeClass: "ui-state-default", 
     hoverClass: "ui-state-hover", 
     drop: function(event, ui) { 
      var newClone = $(ui.helper).clone(); 
      $(this).after(newClone); 
     } 
    }); 
}); 

DEMO

作爲一個評論:我非常recommmend我上述的,因爲它是更好地使克隆在drop事件droppable的方法然後將dragstop事件綁定到draggable。這是因爲否則會產生太多的克隆:我的代碼確保不會生成多餘的克隆。看看我的意思,打開this jsFiddle(它使用錯誤方法:克隆在dragstop),並嘗試刪除可拖動的以外的指定區域。會發生什麼是多餘的克隆將被添加到DOM。這既低效又醜陋,應該避免。

+1

這是一個巨大的幫助。那你 –

+1

你也可以看這裏嗎? http://stackoverflow.com/questions/31221603/remove-cloned-image-after-adding-another-image-with-jquery-ui –

+0

@SaifullahAlam當然:我剛剛提交了一個答案。 –