我想让我的身体在使用鼠标滚轮时停止滚动,而我的网站上的Modal(来自http://twitter.github.com/bootstrap)是打开的。
当模式被打开时,我试图调用下面的javascript片段,但没有成功
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
请注意,我们的网站放弃了对IE6的支持,IE7+需要兼容。
基于此提琴: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');
/* =============================
* 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(); });
});
许多人建议在正文上使用“overflow: hidden”,这是行不通的(至少在我的情况下不是),因为它会让网站滚动到顶部。
这是适用于我的解决方案(手机和电脑),使用jQuery:
$('.yourModalDiv').bind('mouseenter touchstart', function(e) {
var current = $(window).scrollTop();
$(window).scroll(function(event) {
$(window).scrollTop(current);
});
});
$('.yourModalDiv').bind('mouseleave touchend', function(e) {
$(window).off('scroll');
});
这将使模式的滚动工作,并防止网站在同一时间滚动。
当你在另一个模态中使用一个模态时,就会发生上述情况。当我在另一个模态中打开一个模态时,后者的关闭将从主体中移除类modal-open。这个问题的解决取决于你如何关闭后一个模式。
如果你用html关闭模态,
<button type="button" class="btn" data-dismiss="modal">Close</button>
然后你必须像这样添加一个监听器,
$(modalSelector).on("hidden.bs.modal", function (event) {
event.stopPropagation();
$("body").addClass("modal-open");
return false;
});
如果你用javascript关闭模态,
$(modalSelector).modal("hide");
然后你必须在一段时间后像这样运行命令,
setInterval(function(){$("body").addClass("modal-open");}, 300);