Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - 打开模式时防止BODY滚动(Prevent BODY from scrolling when a modal is opened)

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.

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

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

(我试图在模式打开时调用下面的一段javascript,但没有成功)

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

AND

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

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

(请注意,我们的网站放弃了对IE6的支持,不过IE7 +需要兼容。)

  ask by xorinzor translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(在显示模态对话框时,Bootstrap的modal自动将modal-open类添加到主体,并在隐藏对话框时将其删除。)

You can therefore add the following to your CSS:

(因此,您可以将以下内容添加到CSS中:)

body.modal-open {
    overflow: hidden;
}

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.

(您可能会争辩说,上面的代码属于Bootstrap CSS代码库,但这是将其添加到您的站点的简便解决方案。)

Update 8th feb, 2013

(2013年2月8日更新)


This has now stopped working in Twitter Bootstrap v. 2.3.0 -- they no longer add the modal-open class to the body.

(现在,它已在Twitter Bootstrap 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")
});

Update 11th march, 2013 Looks like the modal-open class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll:

(2013年3月11日更新看来, modal-open类将在Bootstrap 3.0中返回,明确地是为了防止滚动:)

Reintroduces .modal-open on the body (so we can nuke the scroll there)

(在主体上重新引入.modal-open(因此我们可以在此处滚动滚动条))

See this: https://github.com/twitter/bootstrap/pull/6342 - look at the Modal section.

(参见: https : //github.com/twitter/bootstrap/pull/6342-参见“ 模态”部分。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...