我想让我的身体在使用鼠标滚轮时停止滚动,而我的网站上的Modal(来自http://twitter.github.com/bootstrap)是打开的。
当模式被打开时,我试图调用下面的javascript片段,但没有成功
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
请注意,我们的网站放弃了对IE6的支持,IE7+需要兼容。
您需要超越@charlietfl的答案并考虑滚动条,否则您可能会看到一个文档回流。
打开模式:
记录身体宽度
将正文溢出设置为隐藏
显式地将主体宽度设置为步骤1中的宽度。
Var $body = $(document.body);
var oldWidth = $body.innerWidth();
美元body.css(“溢出”,“隐藏”);
美元body.width (oldWidth);
关闭模态:
将body overflow设置为auto
将车身宽度设置为auto
Var $body = $(document.body);
美元body.css(“溢出”,“汽车”);
美元body.width(“自动”);
灵感来源:http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php
/* =============================
* Disable / Enable Page Scroll
* when Bootstrap Modals are
* shown / hidden
* ============================= */
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function theMouseWheel(e) {
preventDefault(e);
}
function disable_scroll() {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', theMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = theMouseWheel;
}
function enable_scroll() {
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', theMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = null;
}
$(function () {
// disable page scrolling when modal is shown
$(".modal").on('show', function () { disable_scroll(); });
// enable page scrolling when modal is hidden
$(".modal").on('hide', function () { enable_scroll(); });
});
基于此提琴:http://jsfiddle.net/dh834zgw/1/
下面的代码片段(使用jquery)将禁用窗口滚动:
var curScrollTop = $(window).scrollTop();
$('html').toggleClass('noscroll').css('top', '-' + curScrollTop + 'px');
在你的css中:
html.noscroll{
position: fixed;
width: 100%;
top:0;
left: 0;
height: 100%;
overflow-y: scroll !important;
z-index: 10;
}
现在,当你删除模态时,不要忘记删除html标签上的noscroll类:
$('html').toggleClass('noscroll');
在StackOverflow上做了8-10个小时的研究后,我找到了一个可行的解决方案。
突破
$('.modal').is(':visible');
因此,我已经构建了一个函数来检查是否有任何模态是打开的,它将定期添加类*modal-open**到
setInterval(function()
{
if($('.modal').is(':visible')===true)
{
$("body").addClass("modal-open");
}
else
{
$("body").removeClass("modal-open");
}
},200);
这里使用$(".modal")的原因是所有的模态(在Bootstrap中)都使用类modal (fade/show是根据状态而定)
所以我的模态现在运行完美没有身体得到滚动。
这在GitHub中也是一个bug/闻所未闻的问题,但没有人打扰。