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

当模式被打开时,我试图调用下面的javascript片段,但没有成功

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

AND

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

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


当前回答

你可以试着设置body size为window size, overflow:当modal打开时隐藏

其他回答

为我工作

$('#myModal').on({'mousewheel': function(e) 
    {
    if (e.target.id == 'el') return;
    e.preventDefault();
    e.stopPropagation();
   }
});

你可以使用下面的逻辑,我测试了它,它可以工作(即使在IE中)

   <html>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">

var currentScroll=0;
function lockscroll(){
    $(window).scrollTop(currentScroll);
}


$(function(){

        $('#locker').click(function(){
            currentScroll=$(window).scrollTop();
            $(window).bind('scroll',lockscroll);

        })  


        $('#unlocker').click(function(){
            currentScroll=$(window).scrollTop();
            $(window).unbind('scroll');

        })
})

</script>

<div>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<button id="locker">lock</button>
<button id="unlocker">unlock</button>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

</div>

以上的答案都不适合我。所以我找到了另一种行之有效的方法。

只需添加一个scroll.(命名空间)监听器,并将文档的scrollTop设置为它的最新值…

并在关闭脚本中删除侦听器。

// in case of bootstrap modal example:
$('#myModal').on('shown.bs.modal', function () {
  
  var documentScrollTop = $(document).scrollTop();
  $(document).on('scroll.noScroll', function() {
     $(document).scrollTop(documentScrollTop);
     return false;
  });

}).on('hidden.bs.modal', function() {

  $(document).off('scroll.noScroll');

});

更新

似乎,这不是很好地工作在chrome。有什么建议吗?

大部分的片段都在这里,但我没有看到任何答案把它们放在一起。

这个问题有三个方面。

(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绑定应用到全屏覆盖。

您需要超越@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