Prevent scrolling on mobile browser, without preventing input focusing

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

提交回复
热议问题