如何使用jQuery交换draggables与动画?

时间:2012-12-01 05:15:22

标签: jquery jquery-ui

看起来很简单,但我无法让它发挥作用。我在两个不同的droppables里面有两个可拖动的东西。当我从一个droppable到另一个droppable放置一个draggable时,现有的draggable应该动画移动到另一个可放置的区域。

$('.droppable').droppable({
    hoverClass: 'hoverClass',
    drop: function(event, ui) {
      var $from = $(ui.draggable),
          $fromParent = $from.parent(),
          $to = $(this).children(),
          $toParent = $to.parent();

      // This is where I replace draggables' positions without animation
      $toParent.html($from.css({left: '', top: '', 'z-index': ''}));
      $fromParent.html($to);
      makeDraggable();
    }
});

http://jsfiddle.net/codef0rmer/AywmJ/

1 个答案:

答案 0 :(得分:3)

哇噢!!!我自己想通了。

演示:http://jsfiddle.net/codef0rmer/AywmJ/2/

刚刚编写了这个用于交换的小代码:

function swap($el, fromPos, toPos, duration, callback) {
    $el.css('position', 'absolute')
      .css(fromPos)
      .animate(toPos, duration, function() {
        if (callback) callback();
      });
}

并更新了放弃事件:

$('.droppable').droppable({
    hoverClass: 'hoverClass',
    drop: function(event, ui) {
      var $from = $(ui.draggable),
          $fromParent = $from.parent(),
          $to = $(this).children(),
          $toParent = $(this);

      window.endPos = $to.offset();

      swap($from, $from.offset(), window.endPos, 200);
      swap($to, window.endPos, window.startPos, 1000, function() {
        $toParent.html($from.css({position: 'relative', left: '', top: '', 'z-index': ''}));
        $fromParent.html($to.css({position: 'relative', left: '', top: '', 'z-index': ''}));
        makeDraggable();
      });
    }
});