jQuery UI:开始可拖动之前

在jQueryUI开始拖动之前,如何实现before start事件以更改位置并在draggable元素的DOM中放置?

您可以扩展原型方法:

看看演示

var oldMouseStart = $.ui.draggable.prototype._mouseStart; $.ui.draggable.prototype._mouseStart = function (event, overrideHandle, noActivation) { this._trigger("beforeStart", event, this._uiHash()); oldMouseStart.apply(this, [event, overrideHandle, noActivation]); }; $("#draggable").draggable({ beforeStart: function () { console.log('beforeStart::'); } }); 

我发现作为“helper”选项传递给sortable的方法将在“start”之前调用,并传递(作为第二个参数)已被单击的项。 您可以在此方法中执行您需要执行的操作,然后只返回元素本身(默认的“原始”帮助程序行为)。 我正在使用它来设置我的容器的高度,以便它不会崩溃并触发浏览器窗口的滚动。 这是看起来像:

 $(list).sortable({ helper: function(event, element) { // it's too late if we wait until start to do this $(this).css('height', this.$().height()); return element; } }) 

我不敢访问jQuery UI私有变量,所以我实现了这样:

 // The mouse interaction sequence for dragging starts with a mousedown action. element.on('mousedown', function() { // Mouseup cancels dragging. This is a boring click. element.one('mouseup', function() { element.off('mousemove.mynamespace'); }); // Moving the mouse while holding mousedown is dragging. // This is also what sets off jQuery UI draggable, // but we registered our event listeners first. element.one('mousemove.mynamespace', function() { // !! Your beforeStart code here. }); }); // Initialize jQuery UI draggable AFTER our own event listeners. element.draggable(); 

为此,我使用了mouseup和mousedown:

 var timeout; $('.draggable').mousedown(function() { $('#dragContainer').append($(this)); $(this).css({ top: 0, left: 0 }); }); $('.draggable').draggable(); 

如果mousedown实际上是一次点击而不是拖动,我还使用mouseup来重置旧的父级和位置。

有一个使用distance选项的beforeStart事件会很好,但是我找不到它…