【问题标题】:jQuery UI : Before start draggablejQuery UI:开始可拖动之前
【发布时间】:2013-05-23 13:51:27
【问题描述】:

在jQueryUI开始拖动之前,如何实现before start事件来改变可拖动元素在DOM中的位置和位置?

【问题讨论】:

  • 这个问题连问号都没有,你有没有试过google?

标签: javascript jquery jquery-ui events


【解决方案1】:

我不敢访问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();

【讨论】:

  • 这太棒了。非常感谢!
【解决方案2】:

为此,我使用了 mouseup 和 mousedown:

var timeout;

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

$('.draggable').draggable(); 

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

如果有一个beforeStart 事件与distance 选项一起使用会很好,但我没有找到它...

【讨论】:

  • Mousedown 不会触发拖动,它是 mousedown 后跟 mousemove,除非它被 mouseup 取消。看我的回答。
【解决方案3】:

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

$(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;
  }
})

【讨论】:

    【解决方案4】:

    你可以扩展原型方法:

    SEE DEMO

    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::');
        }
    });
    

    【讨论】:

    • 太棒了。我需要扩展它以捕捉尚不存在的元素并且效果很好!
    猜你喜欢
    • 2014-05-21
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 2011-07-15
    • 2013-02-18
    • 1970-01-01
    • 2013-01-27
    • 2011-03-25
    相关资源
    最近更新 更多