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

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

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

AND

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

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


当前回答

/* =============================
 * 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(); });
});

其他回答

为我工作

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

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

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

这个问题有三个方面。

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

隐藏溢出和固定位置的技巧,但在我的流体设计中,它会固定它超过浏览器宽度,所以宽度:100%固定。

body.modal-open{overflow:hidden;position:fixed;width:100%}

您应该在HTML中添加overflow:隐藏以获得更好的跨平台性能。

我会用

html.no-scroll {
    overflow: hidden;
}