我想让我的身体在使用鼠标滚轮时停止滚动,而我的网站上的Modal(来自http://twitter.github.com/bootstrap)是打开的。
当模式被打开时,我试图调用下面的javascript片段,但没有成功
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
请注意,我们的网站放弃了对IE6的支持,IE7+需要兼容。
大部分的片段都在这里,但我没有看到任何答案把它们放在一起。
这个问题有三个方面。
(1)防止底层页面滚动
$('body').css('overflow', 'hidden')
(2)并移除滚动条
var handler = function (e) { e.preventDefault() }
$('.modal').bind('mousewheel touchmove', handler)
(3)模态解散时进行清理
$('.modal').unbind('mousewheel touchmove', handler)
$('body').css('overflow', '')
如果模式不是全屏,那么将.modal绑定应用到全屏覆盖。
不能让它在Chrome上工作,只是通过改变CSS,因为我不想让页面滚动回顶部。这很有效:
$("#myModal").on("show.bs.modal", function () {
var top = $("body").scrollTop(); $("body").css('position','fixed').css('overflow','hidden').css('top',-top).css('width','100%').css('height',top+5000);
}).on("hide.bs.modal", function () {
var top = $("body").position().top; $("body").css('position','relative').css('overflow','auto').css('top',0).scrollTop(-top);
});
最好的解决方案是大多数答案所使用的css-only body{overflow:hidden}解决方案。一些答案提供了一个修复,也防止“跳跃”造成的消失滚动条;然而,没有一个太优雅。我写了这两个函数,它们看起来工作得很好。
var $body = $(window.document.body);
function bodyFreezeScroll() {
var bodyWidth = $body.innerWidth();
$body.css('overflow', 'hidden');
$body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}
function bodyUnfreezeScroll() {
var bodyWidth = $body.innerWidth();
$body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
$body.css('overflow', 'auto');
}
查看jsFiddle的使用情况。
/* =============================
* 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(); });
});
添加类'is-modal-open'或用javascript修改body标签的样式都是可以的,它会像预期的那样工作。但我们要面对的问题是当body变成overflow:hidden时,它会跳到顶部(scrollTop将变成0)。这将在以后成为一个可用性问题。
作为这个问题的解决方案,而不是改变正文标签溢出:隐藏改变它在html标签
$('#myModal').on('shown.bs.modal', function () {
$('html').css('overflow','hidden');
}).on('hidden.bs.modal', function() {
$('html').css('overflow','auto');
});