2014-01-30 60 views
3

我有一個頁面充滿了可拖動的項目(僅在水平方向)。jQuery UI可拖動和頁面滾動(在手機上)

如果我在觸摸設備上打開我的頁面,我無法向下滾動頁面,顯然是因爲頁面中充滿了可拖動元素。我怎樣才能讓頁面再次滾動?

下面是我使用的可拖動()代碼:

$('li').draggable({ 
axis: 'x', 
drag: function(event, ui) { 
    if(ui.position.left > 0) 
     ui.position.left = 0; 
    if(ui.position.left < -250) 
     ui.position.left = -250; 
} 
}); 

回答

1

萬一有人需要這樣的:

這個問題可以通過使用「處理」的可拖動選項()來解決。 例如,如果我有一個寬度爲500px的div,我可以在其右側(例如)對齊並且寬度爲250px的情況下插入另一個(透明)div。然後我將這個最後的div設置爲可拖動div的句柄。

1

使用手柄是明顯的選擇,但在某些情況下,它不是一種選擇。

在我的場景中,我有一個收件箱列表,其中的項目可以拖動到左側或右側以顯示操作按鈕。整個收件箱項目必須是可拖動的 - 使用拖動手柄將是不直觀的。

如果觸摸是在draggable元素內啓動的,則jQuery的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; 
}); 

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