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

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

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

AND

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

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


当前回答

我读的大多数答案都是关于React的。

我的React功能组件的最佳解决方案是使用@arcticmatt最初提供的解决方案

我在下面的代码示例中包含了一些在其他答案中提到的改进(注意useEffect定义):

import {useEffect, useRef} from "react";

export default function PopoverMenu({className, handleClose, children}) {
  const selfRef = useRef(undefined);

  useEffect(() => {
    const isPopoverOpenned = selfRef.current?.style.display !== "none";
    const focusedElement = document?.activeElement;
    const scrollPosition = {x: window.scrollX, y: window.scrollY};
    if (isPopoverOpenned) {
      preventDocBodyScrolling();
    } else {
      restoreDocBodyScrolling();
    }

    function preventDocBodyScrolling() {
      const width = document.body.clientWidth;
      const hasVerticalScrollBar = (window.innerWidth > document.documentElement.clientWidth);
      document.body.style.overflowX = "hidden";
      document.body.style.overflowY = hasVerticalScrollBar ? "scroll" : "";
      document.body.style.width = `${width}px`;
      document.body.style.position = "fixed";

    }

    function restoreDocBodyScrolling() {
      document.body.style.overflowX = "";
      document.body.style.overflowY = "";
      document.body.style.width = "";
      document.body.style.position = "";
      focusedElement?.focus();
      window.scrollTo(scrollPosition.x, scrollPosition.y);
    }


    return () => {
      restoreDocBodyScrolling(); // cleanup on unmount
    };
  }, []);

  return (
    <>
      <div
        className="backdrop"
        onClick={() => handleClose && handleClose()}
      />
      <div
        className={`pop-over-menu${className ? (` ${className}`) : ""}`}
        ref={selfRef}
      >
        <button
          className="pop-over-menu--close-button" type="button"
          onClick={() => handleClose && handleClose()}
        >
          X
        </button>
        {children}
      </div>
    </>
  );
}

其他回答

我对这段代码不太确定,但值得一试。

jQuery:

$(document).ready(function() {
    $(/* Put in your "onModalDisplay" here */)./* whatever */(function() {
        $("#Modal").css("overflow", "hidden");
    });
});

就像我之前说过的,我不是百分百确定,但还是试一试吧。

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

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

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

这是

body.modal-open {
   overflow: hidden !important;
}

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