打开模态时防止 BODY 滚动 [英] Prevent BODY from scrolling when a modal is opened
问题描述
我希望我的身体在使用鼠标滚轮和 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; });
和
$(window).live('scroll', function() { return false; });
请注意我们的网站不再支持 IE6,但 IE7+ 需要兼容.
Please note our website dropped support for IE6, IE7+ needs to be compatible though.
推荐答案
Bootstrap 的 modal
会在显示模态对话框时自动将 modal-open
类添加到主体中,并且当对话框隐藏时将其删除.因此,您可以将以下内容添加到您的 CSS:
Bootstrap's modal
automatically adds the class modal-open
to the body when a modal dialog is shown and removes it when the dialog is hidden. You can therefore add the following to your CSS:
body.modal-open {
overflow: hidden;
}
您可能会争辩说上面的代码属于 Bootstrap CSS 代码库,但这是将其添加到您的网站的简单修复方法.
You could argue that the code above belongs to the Bootstrap CSS code base, but this is an easy fix to add it to your site.
2013 年 2 月 8 日更新
这现在在 Twitter Bootstrap v. 2.3.0 中已经停止工作——他们不再将 modal-open
类添加到正文中.
一种解决方法是在模态即将显示时将类添加到正文中,并在模态关闭时将其删除:
A workaround would be to add the class to the body when the modal is about to be shown, and remove it when the modal is closed:
$("#myModal").on("show", function () {
$("body").addClass("modal-open");
}).on("hidden", function () {
$("body").removeClass("modal-open")
});
2013 年 3 月 11 日更新看起来 modal-open
类将在 Bootstrap 3.0 中返回,明确用于防止滚动:
Update 11th march, 2013
Looks like the modal-open
class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll:
在身体上重新引入 .modal-open(所以我们可以在那里核弹滚动)
Reintroduces .modal-open on the body (so we can nuke the scroll there)
参见:https://github.com/twitter/bootstrap/pull/6342 - 查看模态部分.
See this: https://github.com/twitter/bootstrap/pull/6342 - look at the Modal section.
这篇关于打开模态时防止 BODY 滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!