Prevent scrolling on mobile browser, without preventing input focusing

和自甴很熟 提交于 2019-11-30 14:19:54

I actually solved this problem on another project, forgot about it, and remembered it most of the way through typing this up.

They key is to just do it on touchmove.

$(document).on('touchmove', function(e) {
    e.preventDefault();
});

However, preventDefault on touchstart does all kinds of nice things like preventing the image save menu on a gesture enabled slideshow. My projects also include this.

$(document).on('touchstart', function(e) {
    if (e.target.nodeName !== 'INPUT') {
        e.preventDefault();
    }
});

If anyone has some suggestions on additional content or how to reformat this so that it can reach a greater audience that would be great. I haven't ever seen the content I have here all in one place, so I felt that it needed to be on SO.

Combine the two!

// prevent scrolling from outside of input field
$(document).on('touchstart', function(e) {
    if (e.target.nodeName !== 'INPUT') {
        e.preventDefault();
    }
});

// prevent scrolling from within input field
$(document).on('touchmove', function(e) {
    if (e.target.nodeName == 'INPUT') {
        e.preventDefault();
    }
});

This probably isn't perfect either, and I am especially worried that the first function will prevent following links, but I'll leave it to others to do extensive tests.

The simple answer to your question is don't use "preventDefault" instead use pointer-events css property to disable the scrolling on the element that scrolls.

CSS for your inputs:

input {
    pointer-events: auto !important;
}

touchstart event listener:

document.body.addEventListener('touchstart', function(e) {
    if (e.target.nodeName === 'INPUT') {
        this.style.pointerEvents = 'none';
    }
});

You will need to reset the pointer-events when you blur the input.

document.body.pointerEvents = 'auto';

+1 Good Question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!