How to prevent background scrolling when Bootstrap

2019-01-08 10:33发布

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.

On mobile browsers (Safari ios, Chrome ios, etc), when a modal is opened and using your finger to scroll it, the background also scrolls as does the modal. How do I prevent that?

20条回答
We Are One
2楼-- · 2019-01-08 11:25

As additional to @Karthick Kumar answer from bootstrap docs

show is triggered at the start of an event

shown is triggered on the completion of an action

... so it should be:

$('.modal')
    .on('show.bs.modal', function (){
            $('body').css('overflow', 'hidden');
        })
    .on('hide.bs.modal', function (){
            // Also if you are using multiple modals (cascade) - additional check
            if ($('.modal.in').length == 1) {
                $('body').css('overflow', 'auto');
            }
        });
查看更多
你好瞎i
3楼-- · 2019-01-08 11:25

I open a modal after a modal and fact the error on modal scrolling, and this css solved my problem:

.modal {
    overflow-y: auto;
    padding-right: 15px;
}
查看更多
Anthone
4楼-- · 2019-01-08 11:26

Prevents the background from scrolling without any fuss.

Also prevents page jumping around from missing scrollbars

body.modal-open {
        position: fixed;
        overflow-y: scroll;
    }
查看更多
The star\"
5楼-- · 2019-01-08 11:28

I've found a simple javascript/jquery solution which utilizes the bootstrap modal events.

My solution also fixes the position:fixed problem where it scrolls the background page all the way back to the top instead of staying in place when modal window is opened/closed.

See details here

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-08 11:29

I know this has been answered but none of these solutions worked for me. I needed to take a different approach. I am using PhoneGap and am compiling my code natively so I had to move the background to the body. I hope this helps someone else. Or if there a cleaner way to do this please feel free to comment...

$(document).on('shown.bs.modal', '.modal', function (e) {

    $("#" + e.target.id).find(".modal-backdrop").css("z-index", $("#" + e.target.id).css("z-index")).insertBefore("#" + e.target.id);

});
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-08 11:33

See here: https://github.com/twbs/bootstrap/issues/7501

So try:

$('body').css('overflow','hidden');
$('body').css('position','fixed');

V3.0.0. should have fixed this issue. Do you use the latest version? If so post an issue on https://github.com/twbs/bootstrap/

查看更多
登录 后发表回答