2014-04-01 96 views
2

我有一個頁面只能在水平方向(在軸X上)放置可拖動的div。垂直滾動的JQuery-UI水平拖動

當我在觸摸設備中時,由於滾動和拖動之間的衝突,我無法向下滾動頁面。

這裏有一個jsfiddle example(在觸摸設備的測試,並試圖滾動)。

我可拖動代碼:

$(".cell").draggable({ 
    axis: "x", 
    drag: function (event, ui) { 
     var size = $(".cell").width(); 

     if (ui.offset.left > size - em(4)) { 
      ui.position.left = size - em(4); 
     } 
    }, 
    start: function (event, ui) { 
     if (initialPosition == null) { 
      initialPosition = ui.position.left; 
     } 

     $(".cell").not(ui.helper).each(function() { 
      var pos = $(this).position().left; 
      if (pos > 0) { 
       $(this).animate({ 
        left: initialPosition 
       }, 200, null); 
      } 
     }); 
    }, 
    stop: function (event, ui) { 
     var size = $(".cell").width(); 
     if (ui.position.left > initialPosition) { 
      if (ui.position.left - initialPosition >= size/3) { 
       ui.helper.animate({ 
        left: size - em(4) 
       }, 200, null); 
      } else { 
       ui.helper.animate({ 
        left: initialPosition 
       }, 200, null); 
      } 
     } 
    } 
}); 

我想如果用戶垂直滾動,然後再開始拖動並取消 水平拖動來檢測。

請幫助我。我該如何做這項工作?

+0

我會建議使用浮動按鈕來上下移動。 –

回答

-2

我用jquery.ui.touch-punch.js這個工作對我來說,第38行:

event.preventDefault(); 

Reference

+0

請在答案中提供代碼的主要部分。如果在未來的鏈接被破壞,你的答案將是無用的。謝謝 – acostela

1

我有類似這樣的問題,最終找到了一個相當簡單的解。

在我的情況我有一個收件箱列表,它,你可以拖動到左側或右側,露出操作按鈕的項目。整個收件箱項目必須是可拖動的 - 所以拖動手柄的使用不是一個選項。

jQuery的draggable防止垂直滾動條上的觸摸屏,如果觸摸了一個draggable元素內啓動。因此,如果屏幕上充滿了可拖動的收件箱項目,那麼用戶將陷入困境 - 無法向上或向下滾動。

爲我工作的解決辦法是測量光標的垂直位置的變化,並使用window.scrollBy相同的量,手動滾動窗口:

var firstY = null;  
var lastY = null; 
var currentY = null; 
var vertScroll = false; 
var initAdjustment = 0; 

// record the initial position of the cursor on start of the touch 
jqDraggableItem.on("touchstart", function(event) { 
    lastY = currentY = firstY = event.originalEvent.touches[0].pageY; 
}); 

// fires whenever the cursor moves 
jqDraggableItem.on("touchmove", function(event) { 
    currentY = event.originalEvent.touches[0].pageY; 
    var adjustment = lastY-currentY; 

    // Mimic native vertical scrolling where scrolling only starts after the 
    // cursor has moved up or down from its original position by ~30 pixels. 
    if (vertScroll == false && Math.abs(currentY-firstY) > 30) { 
     vertScroll = true; 
     initAdjustment = currentY-firstY; 
    } 

    // only apply the adjustment if the user has met the threshold for vertical scrolling 
    if (vertScroll == true) { 
     window.scrollBy(0,adjustment + initAdjustment); 
     lastY = currentY + adjustment; 
    } 

}); 

// when the user lifts their finger, they will again need to meet the 
// threshold before vertical scrolling starts. 
jqDraggableItem.on("touchend", function(event) { 
    vertScroll = false; 
}); 

一個觸摸屏設備上這將密切模擬天然滾動。