5

如果可拖动的元素被还原,有没有办法获取信息?

我坚持这一点。我想让一个元素再次可放置,但前提是放置在那里的可拖动元素移动到其他地方(意思是不会恢复)。

4

3 回答 3

23

我发现无法获取有关对象是否已恢复的信息它内置在 jQuery 中,但显然没有很好的文档记录。

本质上,它是通过对可拖动对象的恢复选项使用回调函数来完成的。

类似于以下内容:

$(".myselector").draggable(
{
  revert: function(droppableObj)
  {
     //if false then no socket object drop occurred.
     if(droppableObj === false)
     {
        //revert the .myselector object by returning true
        return true;
     }
     else
     {
        //droppableObj was returned,
        //we can perform additional checks here if we like
        //alert(droppableObj.attr('id')); would work fine

        //return false so that the .myselector object does not revert
        return false;
     }
  }
});

有关详细信息,请参阅http://www.agilepro.com/blog/2009/12/while-this-functionality-is-built-into.html 。

于 2010-08-05T19:13:43.020 回答
9

看起来 jQuery UI 不支持它,所以你可以像这样自己添加它:

$.ui.draggable.prototype._mouseStop = function(event) {
    //If we are using droppables, inform the manager about the drop
    var dropped = false;
    if ($.ui.ddmanager && !this.options.dropBehaviour)
        dropped = $.ui.ddmanager.drop(this, event);

    //if a drop comes from outside (a sortable)
    if(this.dropped) {
        dropped = this.dropped;
        this.dropped = false;
    }

    if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
        var self = this;
        self._trigger("reverting", event);
        $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
            event.reverted = true;
            self._trigger("stop", event);
            self._clear();
        });
    } else {
        this._trigger("stop", event);
        this._clear();
    }

    return false;
}

将允许您这样做:

$(document).ready(function($) {
    $('#draggable').draggable({
        revert: true,
        reverting: function() {
            console.log('reverted');
        },
        stop: function(event) {
            if (event.reverted) {
                console.log('reverted');
            }
        }
    });
});
于 2009-12-05T23:20:04.000 回答
1

扩展@mbeedub 的解决方案,这是我自己的解决方案。就我而言,我需要ui.positionon的值stop。如果拖动被还原,那么我需要将对象返回到其原始位置。不幸的是,运行还原动画后,jQuery UI 不会更新position属性。幸好有originalPosition房产。所以只要我能检测到恢复的状态(在这种情况下,通过类名),我就没事!

function updatePosition (position) {
  /* Posting position to server */
}

element.draggable({

  drag: function (event, ui) {
    updatePosition(ui.position);
  },

  revert: function (droppable) {
    return !droppable && element.addClass('ui-draggable-reverted');
  },

  stop: function (event, ui) {
    if (element.is('.ui-draggable-reverted')) {
      updatePosition(ui.originalPosition);
      element.removeClass('ui-draggable-reverted');
    } else {
      updatePosition(ui.position);
    }
  }
});
于 2013-01-18T21:40:32.663 回答