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

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

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

AND

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

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


当前回答

当你在另一个模态中使用一个模态时,就会发生上述情况。当我在另一个模态中打开一个模态时,后者的关闭将从主体中移除类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);

其他回答

当你在另一个模态中使用一个模态时,就会发生上述情况。当我在另一个模态中打开一个模态时,后者的关闭将从主体中移除类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);

我使用这个香草js函数添加“模态打开”类的身体。(根据smhmic的回答)

function freezeScroll(show, new_width)
{
    var innerWidth = window.innerWidth,
        clientWidth = document.documentElement.clientWidth,
        new_margin = ((show) ? (new_width + innerWidth - clientWidth) : new_width) + "px";

    document.body.style.marginRight = new_margin;
    document.body.className = (show) ? "modal-open" : "";
};

许多人建议在正文上使用“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');
    });

这将使模式的滚动工作,并防止网站在同一时间滚动。

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

为我工作

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