Prevent scrolling on mobile browser, without preventing input focusing

前端 未结 3 1359
轻奢々
轻奢々 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: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.

提交回复
热议问题