简体   繁体   中英

jQuery draggable/droppable clone and remove issues

I am trying to create a simple app using jQuery UI. I have two divs, one is a "droppable" container , the other is a div containing three(or more) images and they are draggable .

I want users to be able to add up to three images to the container.

Here is my JS Fiddle Demo

Key functionality: (a) User can drag image and drop inside of the container. The images should be aligned. (b) User can sort images after images have been dropped. (c) When images being dragging out of the "droppable" containe r, it should be removed from the container .

Issues: (a) When there is only one image in the "droppable" area, it creates a clone of that image whenever dragging it around. It also messes up the alignment. I am thinking it probably has something to do with the "helper: clone" option. However, when I've already added three images to the container, I didn't see this error. (b) I couldn't figure out how to implement the remove function.

Any help is greatly appreciated!!!! Thank you in advance!

HTML:

<div id="demo">
</div>

<div class="parameter">
  <div class="option" id="tab"></div>
  <div class="option" id="dual"></div>
  <div class="option" id="standard"></div>
</div>

JS:

$(document).ready(function() {
  $(".option").draggable({
    helper: "clone",
    opacity: 0.5,
    appendTo: "#demo"
  })

  $("#demo").droppable({
    accept: ".option",
    drop: function(event, ui) {
      if (document.getElementsByClassName("option").length <= 6) {
        ui.draggable.clone().appendTo($(this))
      }
    }
  })

  $("#demo").sortable()
})

Working Example: https://jsfiddle.net/Twisty/q09m84er/

JavaScript

$(function() {
  $(".option").draggable({
    helper: "clone",
    opacity: 0.5,
    connectToSortable: "#demo"
  });

  $("#demo").sortable({
    axis: "y",
    items: "> div.option",
    receive: function(event, ui) {
      if ($("#demo .option").length <= 6) {
        var item = ui.helper;
        var type = ui.item.attr("id");
        var count = $("#demo div[id|='" + type + "']").length;
        item.attr("id", type + "-" + ++count);
        item.appendTo($(this));
      } else {
        return false;
      }
    }
  });
});

a) User can drag option from list to sortable

b) User can sort after dragging

c) Is more difficult. I would advise creating an icon or dropzone that the item can be dragged to that will cause it to be removed. Personally, I would append a button to the item to remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM