简体   繁体   中英

jQuery UI draggable has jerky transition on drop

I have a simple drag and drop functionality that I'm attempting to get working. I have cards that are draggable and can be dropped on top of other cards to swap positions with the other card. Here's a fiddle with the functionality in place: https://jsfiddle.net/vj0a9gp8/1/

The drag and drop code is pretty simple:

$(function() {
  $(".card").  draggable({
    revert: true
  }).  droppable({
    hoverClass: "card-hover",
    drop: function(event, ui) {
      swapNodes($(this).get(0), $(ui.draggable).get(0));
    }
  });
});


function swapNodes(a, b) {
  var aparent = a.parentNode;
  var asibling = a.nextSibling === b ? a : a.nextSibling;
  b.parentNode.insertBefore(a, b);
  aparent.insertBefore(b, asibling);
}

Basically when a card is dragged and then dropped onto another, the swapNodes function traverses up the dom and places them where they belong. This all works great. The issue, which you can see in the fiddle, is that when the drop occurs the dropped card kind of jerks off screen before animating in to place and it looks poorly overall. I've tried playing around with draggable.position to address and fix this functionality but all I've managed to do is make it worse. Any ideas?

When you drag your element, it changes the left and top position. When you drop it, you change its position in the DOM, but you never specify a new top and left, so it still keeps the one set when dragging it. The animation is there because you have a revert to true, which puts back the original position and animates it.

Easy solution would be to set revert to 'invalid' (so only if there's no drop) and set the left and top in your swap function. Like this

revert: 'invalid'
...
b.style.left = '';
b.style.top = '';

https://jsfiddle.net/huw2Lkgb/1/

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