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

后端 未结 20 1444
抹茶落季
抹茶落季 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:54

    I tried the accepted answer which prevented the body from scrolling but had the issue of scrolling to the top. This should solve both issues.

    As a side note, it appears overflow:hidden doesn't work on body for iOS Safari only as iOS Chrome works fine.

    var scrollPos = 0;
    
    $('.modal')
        .on('show.bs.modal', function (){
            scrollPos = $('body').scrollTop();
            $('body').css({
                overflow: 'hidden',
                position: 'fixed',
                top : -scrollPos
            });
        })
        .on('hide.bs.modal', function (){
            $('body').css({
                overflow: '',
                position: '',
                top: ''
            }).scrollTop(scrollPos);
        });
    

提交回复
热议问题