ドラッグ可能な要素が元に戻された場合に情報を取得する方法はありますか?
私はこれにこだわっています。要素を再びドロップ可能にしたいのですが、そこに横たわっていたドラッグ可能要素が別の場所に移動された場合に限ります (意味は元に戻りません)。
オブジェクトが復帰したかどうかについての情報を取得する方法があることがわかりました。それは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を参照してください。
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');
}
}
});
});
@mbeedub のソリューションを拡張して、これが私自身のソリューションです。私の場合、ui.position
onの値が必要stop
です。ドラッグが元に戻った場合は、オブジェクトを元の位置に戻す必要があります。position
残念ながら、元に戻すアニメーションが実行された後、jQuery UI はプロパティを更新しません。幸いなことに、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);
}
}
});