打开模式时防止BODY滚动

JavaScript CSS

凯西里

2020-03-22

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

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

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

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

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

第2566篇《打开模式时防止BODY滚动》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
樱A 2020.03.22

您可以尝试将主体尺寸设置为带有溢出的窗口尺寸:模式打开时隐藏

飞云 2020.03.22

您需要超越@charlietfl的答案并考虑滚动条,否则可能会看到文档重排。

打开模式:

  1. 记录body宽度
  2. body溢出设置hidden
  3. 将主体宽度显式设置为步骤1中的宽度。

    var $body = $(document.body);
    var oldWidth = $body.innerWidth();
    $body.css("overflow", "hidden");
    $body.width(oldWidth);
    

关闭模式:

  1. body溢出设置auto
  2. body宽度设置auto

    var $body = $(document.body);
    $body.css("overflow", "auto");
    $body.width("auto");
    

灵感来源:http : //jdsharp.us/jQuery/minute/calculate-scrollbar-width.php

Tony凯 2020.03.22

可接受的答案不适用于移动设备(至少是装有Safari 7的iOS 7和Safari 7),并且我不希望CSS支持时在我的网站上运行MOAR JavaScript。

此CSS可以防止背景页面在模式下滚动:

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

但是,它也具有基本滚动到顶部的轻微副作用。position:absolute解决了此问题,但重新引入了在移动设备上滚动的功能。

如果您知道您的视口(我的插件将视口添加到<body>),您只需添加一个CSS切换器position

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;
}
body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute; 
}

我还添加了此选项,以防止显示/隐藏模式时基础页面向左/向右跳转。

body {
    // STOP MOVING AROUND!
    overflow-x: hidden;
    overflow-y: scroll !important;
}

这个答案是x-post。

斯丁前端 2020.03.22

在显示模式对话框时,Bootstrap会modal自动将类添加modal-open到主体,而在对话框隐藏时将其删除。因此,您可以将以下内容添加到CSS中:

body.modal-open {
    overflow: hidden;
}

您可能会争辩说,上面的代码属于Bootstrap CSS代码库,但这是将其添加到您的站点的简单解决方案。

2013年2月8日更新
该程序现已在Twitter Bootstrap 2.3.0版中停止工作-他们不再将此类添加modal-open到正文中。

一种解决方法是在要显示模式时将类添加到主体,并在关闭模式时将其删除:

$("#myModal").on("show", function () {
  $("body").addClass("modal-open");
}).on("hidden", function () {
  $("body").removeClass("modal-open")
});

Update 11th march, 2013 Looks like the modal-open class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll:

Reintroduces .modal-open on the body (so we can nuke the scroll there)

See this: https://github.com/twitter/bootstrap/pull/6342 - look at the Modal section.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android