打开模态时防止BODY滚动 [英] Prevent BODY from scrolling when a modal is opened

查看:95
本文介绍了打开模态时防止BODY滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的身体在Modal时使用鼠标滚轮停止滚动(来自 http://twitter.github。 com / bootstrap )在我的网站上打开。

I want my body to stop scrolling when using the mousewheel while the Modal (from http://twitter.github.com/bootstrap) on my website is opened.

我打算在打开模态时调用下面的javascript但没有成功

I've tried to call the piece of javascript below when the modal is opened but without success

$(window).scroll(function() { return false; });

AND

$(window).live('scroll', function() { return false; });

请注意我们的网站不支持IE6,但IE7 +需要兼容。

Please note our website dropped support for IE6, IE7+ needs to be compatible though.

推荐答案

接受的答案不适用于移动设备(至少iOS 7至Safari 7),我不希望运行MOAR JavaScript CSS会做我的网站。

The accepted answer doesn't work on mobile (iOS 7 w/ Safari 7, at least) and I don't want MOAR JavaScript running on my site when CSS will do.

这个CSS会阻止背景页面在模态下滚动:

This CSS will prevent the background page from scrolling under the modal:

body.modal-open {
    overflow: hidden;
    position: fixed;
}

然而,它也有轻微的副作用,基本上滚动到顶部。 position:absolute 解决此问题,但重新介绍了在移动设备上滚动的功能。

However, it also has a slight side-affect of essentially scrolling to the top. position:absolute resolves this but, re-introduces the ability to scroll on mobile.

如果您知道自己的视口(我的插件,用于将视口添加到< body> )你可以为位置添加一个css切换。

If you know your viewport (my plugin for adding viewport to the <body>) you can just add a css toggle for the position.

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;
}
body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute; 
}






我也将此添加到在显示/隐藏模态时阻止底层页面向左/向右跳跃。


I also add this to prevent the underlying page from jumping left/right when showing/hiding modals.

body {
    // STOP MOVING AROUND!
    overflow-x: hidden;
    overflow-y: scroll !important;
}

这个答案是一个x-post。

这篇关于打开模态时防止BODY滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆