【问题标题】:jQuery UI Draggable and Page Scrolling (on mobile)jQuery UI 可拖动和页面滚动(在移动设备上)
【发布时间】:2014-01-30 16:03:02
【问题描述】:

我有一个充满可拖动项目的页面(仅限水平)。

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

这是我正在使用的 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;
}
});

【问题讨论】:

    标签: jquery iphone jquery-ui mobile scroll


    【解决方案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;
    });
    

    这将非常模仿触摸设备上的原生滚动。

    【讨论】:

      【解决方案2】:

      以防万一有人需要:

      这个问题可以通过使用draggable()的“handle”选项来解决。 例如,如果我有一个宽度为 500 像素的 div,我可以在其中插入另一个(透明的)div,向右对齐(例如),宽度为 250 像素。然后我将最后一个 div 设置为可拖动 div 的句柄。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2013-11-20
        相关资源
        最近更新 更多