簡體   English   中英

使用jQuery UI添加另一個圖像后刪除克隆的圖像

[英]Remove cloned image after adding another image with jQuery UI

我從上一個問題中得到了一個很好的解決方案,即在刪除后成功克隆圖像。

這是代碼:

$(function() {
var makeDraggable = function(element) {
    element.draggable({ 
        revert: "invalid",
        appendTo: "#droppable",
        helper: "clone" 
    });
}
$( "#droppable" ).droppable({
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function(event, ui) {
        var newClone = $(ui.helper).clone();
        makeDraggable(newClone);
        $(this).after(newClone);
    }
});
// Initalise the program by making first draggable:
makeDraggable($(".draggable img"));

但問題是我想在目標區域一次只顯示一個圖像。 但目前顯示所有丟棄的圖像。

更具體地說,當用戶在目標區域中放下圖像並隨后拖動另一圖像時,應該從放下的或目標區域中移除先前的圖像,並且在目標區域中僅應該看到新圖像。 看到這個演示: jsFiddle示例

我該如何解決這個問題?

在drop方法中,而不是像這樣使用.after使用.append()

drop: function(event, ui) {
  var newClone = $(ui.helper).clone();
  makeDraggable(newClone);
  $(this).children(':not(span)').remove(); // <--- this will remove all the elements which are not a span before appending
  $(this).append(newClone);
}

另外,不要在div內部寫drop drop#droppable使用這樣的span

<div id="droppable">
  <span>drop</span>
</div>

這是一個演示http://jsfiddle.net/dhirajbodicherla/e3pf6ays/14/

您使用以下代碼一個接一個地添加克隆。

$(this).after(newClone);

您需要做的就是:清空droppable容器,然后添加新的克隆,如下所示:

drop: function(event, ui) {
    var newClone = $(ui.helper).clone();
    makeDraggable(newClone);
    $(this).empty().append(newClone);
}

更新了小提琴

我不會像其他答案那樣簡單地清空droppable目標區域,而是在已刪除的項目中添加一個類,然后在新的draggabledragstart事件中刪除它們。 此外,在選擇新的draggable時添加一個小的fadeOut()事件會很不錯。 但是,正如Ishettyl指出的那樣,如果用戶決定不刪除可拖動的元素,那么還必須再次對該元素進行fadeIn() 這可以使用自定義revert功能完成(見下文)。

結果是這樣的:

在此輸入圖像描述

在我看來,這看起來更優雅,並且不會混淆用戶是否允許更多項目。

$(function() {
    $(".draggable img").draggable({ 
        revert: function (socketObj) {
            if (!socketObj) {
                if ($(this).hasClass("droppedItems")) {
                    $(this).fadeOut(function() {
                        $(this).remove();
                    });
                } else {
                    $(".droppedItems").fadeIn();
                    return true;   
                }
            }
        },
        helper: "clone",
        start: function(event, ui) {
            $(".droppedItems").fadeOut();
        }
    }); 
    $( "#droppable" ).droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function(event, ui) {
            $(".droppedItems").remove();
            var newClone = $(ui.helper).clone();
            newClone.addClass("droppedItems");
            $(this).append(newClone);
        }
    });
});

DEMO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM