Prevent scrolling on mobile browser, without preventing input focusing

前端 未结 3 1338
轻奢々
轻奢々 2021-01-02 22:41

I use preventDefault() on touchstart on the document to prevent scrolling on a page. Unfortunately this prevents too much. The user can no longer give focus to an input (a

相关标签:
3条回答
  • 2021-01-02 23:07

    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.

    0 讨论(0)
  • 2021-01-02 23:10

    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

    0 讨论(0)
  • 2021-01-02 23:11

    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.

    0 讨论(0)
提交回复
热议问题