【发布时间】:2013-05-23 13:51:27
【问题描述】:
在jQueryUI开始拖动之前,如何实现before start事件来改变可拖动元素在DOM中的位置和位置?
【问题讨论】:
-
这个问题连问号都没有,你有没有试过google?
标签: javascript jquery jquery-ui events
在jQueryUI开始拖动之前,如何实现before start事件来改变可拖动元素在DOM中的位置和位置?
【问题讨论】:
标签: javascript jquery jquery-ui events
我不敢访问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 重置旧的父级和位置。
如果有一个beforeStart 事件与distance 选项一起使用会很好,但我没有找到它...
【讨论】:
我发现作为“助手”选项传递给可排序的方法将在“开始”之前被调用,并传递(作为第二个参数)已单击的项目。您可以在此方法中执行您需要执行的操作,然后只返回元素本身(默认的“原始”助手行为)。我正在使用它来设置容器的高度,以便它不会折叠并触发浏览器窗口的滚动。看起来是这样的:
$(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;
}
})
【讨论】:
你可以扩展原型方法:
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::');
}
});
【讨论】: