How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

后端 未结 20 1494
抹茶落季
抹茶落季 2020-12-01 01:45

How to prevent background scrolling when Bootstrap 3 modal open on mobile platforms? On desktop browsers the background is prevented from scrolling and works as it should.<

20条回答
  •  心在旅途
    2020-12-01 01:52

    Using position:fixed has the side effect of scrolling the body to the top.

    If you do not your body to scroll to the top, DO NOTE use position:fixed. Just disable touchmove on the body if the modal is open. Note: The modal itself is still able to scroll on touch (if larger than the screen).

    CSS:

    body.modal-open {
        overflow: hidden;
        width: 100%;
        /* NO position:fixed here*/
    }
    

    JS:

    $('.modal').on('show.bs.modal', function (ev) { // prevent body from scrolling when modal opens
        $('body').bind('touchmove', function(e){
            if (!$(e.target).parents().hasClass( '.modal' )){ //only prevent touch move if it is not the modal
                e.preventDefault()
            }
        })
    })
    $('.modal').on('hide.bs.modal', function (e) { //unbind the touchmove restrictions from body when modal closes
        $('body').unbind('touchmove');
    })
    

    EDIT: Note, for very small modals, you might have to add the following line to your CSS:

    .modal-dialog{
        height: 100%;
    }
    

提交回复
热议问题