简体   繁体   中英

jQuery UI Draggable and Droppable Return to Original Position Only

Codepen here: https://codepen.io/anon/pen/weZwVx

I have some images that are draggable. I need them to be returned to their original position only . So essentially even if they are dragged back to the wrong spot they will snap to their original position in the table.

Right now when you drag it back to the original position it can be added to another td even it contains another image. The image should be able to be dropped in the purple box and then if someone moves it back to the black table it should go back to it's original position only, even if it is dragged back to another spot.

Here's the JS:

$( ".emojis" ).draggable({
                revert : function(event, ui) {
        $(this).data("ui-draggable").originalPosition = {
            top : 0,
            left : 0
        };
        return !event;
    }
});
            $('#drop-em').droppable({
                drop: function(ev, ui) {
                    $(ui.draggable).detach().css({top: 0,left: 0}).appendTo(this);
                }

            });
            $('#emoji-table td').droppable({
                drop: function(ev, ui) {


                    $(ui.draggable).detach().css({top: 0,left: 0}).prependTo(this);

                }

            });

I think the easiest way based on the code you provided would be to set a matching id to the and elements, that way when the image is being dropped, it can check to see if the id's match each other. If they don't match, you just send the image to the correct element.

  $( ".emojis" ).draggable({
    revert : function(event, ui) {
    // on older version of jQuery use "draggable"
    // $(this).data("draggable")
    // on 2.x versions of jQuery use "ui-draggable"
    // $(this).data("ui-draggable")
    var bRevertingImg = this.parent("#drop-em");

    //Only apply logic when reverted
    //needed since this function is called anytime .emoji is dropped
    if (!bRevertingImg.length) {
      var imgID = $(this).data("id");
      var cellID = $(this).parent().data("id");

      //If the child and parent ids don't match, we move the child to the correct parent
      if (imgID !== cellID) {
        var correctCell = $("#emoji-table").find("td[data-id='" + imgID + "']");
        correctCell.prepend(this)        
      }

      // return boolean
    }
    return !event;   

    // that evaluate like this:
    // return event !== false ? false : true;
  }
});

I edited your codepen to show it in action here

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