jQuery UI拖动和页面滚动(在移动设备上)

4

我有一个页面,其中充满了可拖动的项目(仅水平方向)。

如果我在触摸设备上打开我的页面,我无法向下滚动页面,显然是因为页面充满了可拖动元素。如何使页面再次可滚动?

这是我正在使用的draggable()代码:

$('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;
}
});
2个回答

2
使用手柄是显而易见的选择,但在某些情况下并不可行。在我的场景中,我有一个收件箱列表,其中的项目可以向左或向右拖动以显示操作按钮。整个收件箱项目必须可拖动--使用拖动手柄会让人感到不直观。
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;
});

这将紧密模拟触摸设备上的本地滚动。

1

如果有人需要,可以使用draggable()的"handle"选项来解决问题。 例如,如果我有一个宽度为500px的div,我可以在其中插入另一个(透明)div,对齐到右侧(例如),并且宽度为250px。然后将此最后一个div设置为可拖动div的手柄。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接