移动Safari:禁用"屏幕外"滚动页面

noo*_*ber 2 iphone mobile-safari touch

我想阻止滚动页面"从iPhone屏幕外"(当页面边框后面的灰色Safari的背景可见时).要做到这一点,我正在取消touchmove事件:

// Disables scrolling the page out of the screen.
function DisableTouchScrolling()
{
    document.addEventListener("touchmove", function TouchHandler(e) { e.preventDefault(); }, true);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这也禁用了mousemove事件:当我点击一个按钮然后将我的手指移出它,然后释放屏幕,无论如何都会触发按钮的onclick事件.

我已经尝试在鼠标事件上映射触摸事件,如下所示:http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/ ,但无效(相同的行为) ).

有任何想法吗?

MrG*_*mez 7

根据我对你的问题的理解,你试图将你上面提到的代码Ross Boucher在Posterous上提供的代码片段结合起来.尝试将这两个片段背靠背组合将无法正常工作,因为在禁用时touchmove,您还禁用了允许mousemove通过其样本工作的填充程序.

这个问题及其答案为您的问题制定了可行的解决方案.您应该尝试这两个代码段以查看它们是否可以解决您的问题:

此代码段会禁用旧的滚动行为:

elementYouWantToScroll.ontouchmove = function(e) {
    e.stopPropagation();
}; 
Run Code Online (Sandbox Code Playgroud)

或者这个,来自同一个:

document.ontouchmove = function(e) {
    var target = e.currentTarget;
    while(target) {
        if(checkIfElementShouldScroll(target))
            return;
        target = target.parentNode;
    }

    e.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)

然后,放入Posterous上的代码:

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
         switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="mouseup"; break;
        default: return;
    }

             //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //           screenX, screenY, clientX, clientY, ctrlKey, 
    //           altKey, shiftKey, metaKey, button, relatedTarget);

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                              first.screenX, first.screenY, 
                              first.clientX, first.clientY, false, 
                              false, false, false, 0/*left*/, null);

                                                                                 first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

那应该为你做.如果没有,则其他内容无法与Mobile Safari一起使用.