2012-03-06 29 views
6

我正在尝试将jQuery UI的可拖动功能与jQuery Mobile的taphold事件相结合的移动应用程序。这个想法是一个元素在执行taphold时变得可拖动。结合jQuery Mobile taphold和jQuery UI可拖动

可拖动正在初始化在下列代码元素:

$('div.rect', '#outerBox').draggable({ 
    containment: "parent", 
    grid: [50, 50], 
    disabled: true, 
    stop: function(event, ui) { 
     $(this).draggable('disable'); 
     $(this).removeClass('highlighted'); 
    } 
}); 

正如你所看到的可拖动功能最初是被禁用的,因为我想taphold事件后启用它。要做到这一点我目前使用下面的代码:

// Bind long press event to rectangle elements 
$('div.rect', '#outerBox').bind('taphold', function(event, ui) { 
    // Enable dragging on long press 
    $(this).addClass('highlighted'); 
    $(this).draggable('enable'); 
}); 

这工作,但问题是,“释放轻敲-again'事件需要以拖动元素,而不是拖拽事件后直接拖动。 这可能是某种事件干扰问题?我尝试了像event.preventDefault()之类的东西,但是我对jQuery事件的了解并不多,所以我不知道这是否会产生任何影响。

有关如何解决这个问题的任何想法?

+0

您的代码可以正常使用jQuery Mobile 1.4.4+,不需要以下建议的解决方法。 –

回答

1

首先,jQuery UI可拖动不适用于触摸事件。我假设你已经做了必要的调整来解决这个问题。

I.e.见Jquery-ui sortable doesn't work on touch devices based on Android or IOS

接下来我会说touchstart事件没有流过,因为在jquery mobile中已经实现了taphold。

可拖动只会在启动touchstart/mousedown事件时启动。

我以前见过类似的东西,但是有一个可拖动的doubletap。

您可能需要手动触发taphold事件处理程序内的touchstart事件可拖动在踢:

$('div.rect', '#outerBox').bind('taphold', function(event, ui) { 
    var offset = $(this).offset(); 
    var type = $.mobile.touchEnabled ? 'touchstart' : 'mousedown'; 
    var newevent = $.Event(type); 
    newevent.which = 1; 
    newevent.target = this; 
    newevent.pageX = event.pageX ? event.pageX : offset.left; 
    newevent.pageY = event.pageY ? event.pageX : offset.top; 

    $(this).trigger(newevent); 
}); 
+0

使用jQuery UI Touch Punch [链接](http://touchpunch.furf.com/)使用jQuery拖放作品 – martinoss

+0

@martinoss对不起,但这不适用于iOS。请参阅http://stackoverflow.com/q/36013627/582727 – Daniel

1

虽然晚了一点 - 我这通过跳过taphold插件,并使用这个工作代替。 请记住添加Touch Punch

$('#whatever').on('touchstart', function (event) { 
    var me = this; 

    if (!me.touching) { 
     if (me.touched) { clearTimeout(me.touched); }; 
     me.touched = setTimeout(function() { 
      //console.log('taphold'); 

      //Prevent context menu on mobile (IOS/ANDROID) 
      event.preventDefault(); 

      //Enable draggable 
      $this.draggable('enable'); 

      //Set internal flag 
      me.touching = true; 

      //Add optional styling for user 
      $(me).addClass('is-marked'); 

      //trigger touchstart again to enable draggable through touch punch 
      $(me).trigger(event); 

      //Choose preferred duration for taphold 
     }, 500); 
    } 
}).on('touchend', function() { 
    //console.log('touchend'); 
    this.touching = false; 

    //Disable draggable to enable default behaviour 
    $(this).draggable('disable'); 

    //Remove optional styling 
    $(this).removeClass('is-marked'); 

    clearTimeout(this.touched); 
}).on('touchmove', function() { 
    //console.log('touchmove'); 

    clearTimeout(this.touched); 
});