开发者

Prevent scrolling in Android browser

开发者 https://www.devze.com 2023-03-16 18:33 出处:网络
Is there a way to prevent scrolling of a rendered HTML page in the Android browser? The following does not appear to have any impact on page scrolling in the Android browser:

Is there a way to prevent scrolling of a rendered HTML page in the Android browser? The following does not appear to have any impact on page scrolling in the Android browser:

var preventDefault = function(e) {
    e.preventDefault();
    return false;
};
document.addEventListener('touchmove',preventDefault,false);
document.body.addEventListener('touchmove',preventDefault,true);
window.addEventListener('touchmove',preventDefault,true);

(I've tried with bubbling on and off.)

It looks to me like Android Webkit makes the "window" the same length as the document, so scrolling is being done on the browser itself, not on the document body or DOM window obj开发者_JAVA技巧ect. What's weird is that that's exactly what webkit on iOS does, but the code above still works.


Answering my own question.

The problem ended up being that you need to capture and suppress ontouchstart as well as ontouchmove on document to stop the browser from scrolling. This is definitely different in iOS, but it still works identically on both platforms.

The actual code I ended up using looks sort of like this:

var preventDefault = function(e){
    e.preventDefault();
};
var touchstart = function(e) {
    document.addEventListener('touchstart', preventDefault,false);
    document.addEventListener('touchmove',  preventDefault,false);
    /*do other stuff*/
};
var touchend = function(e) {
    document.removeEventListener('touchstart', preventDefault,false);
    document.removeEventListener('touchmove',  preventDefault,false);
};

element.addEventListener('touchstart',  touchstart, false);
element.addEventListener('touchend',    touchend,   false);


Not works on Chrome on Android though

But preventing event on window and stopping immediate propagation helps!

Handler should be not passive to do that.

MAY BE adding an event handler on capturing phase would help too

But this snippet below is tested by me

window.addEventListener("touchmove", function(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
}, { passive: false });

DEMO https://codepen.io/ColCh/full/qvLqoe

0

精彩评论

暂无评论...
验证码 换一张
取 消