我想让我的身体在使用鼠标滚轮时停止滚动,而我的网站上的Modal(来自http://twitter.github.com/bootstrap)是打开的。
当模式被打开时,我试图调用下面的javascript片段,但没有成功
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
请注意,我们的网站放弃了对IE6的支持,IE7+需要兼容。
接受的答案不工作在手机上(iOS 7 w/ Safari 7,至少),我不希望MOAR JavaScript运行在我的网站上,当CSS将做。
这个CSS将阻止后台页面在模式下滚动:
body.modal-open {
overflow: hidden;
position: fixed;
}
然而,它也有一个轻微的副作用,基本上是滚动到顶部。位置:绝对解决了这个问题,但是,重新引入了在移动设备上滚动的能力。
如果你知道你的视口(我的插件为<body>添加视口),你可以为这个位置添加一个css切换。
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。
我读的大多数答案都是关于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>
</>
);
}
试试下面的代码:
$('.entry_details').dialog({
width:800,
height:500,
draggable: true,
title: entry.short_description,
closeText: "Zamknij",
open: function(){
// blokowanie scrolla dla body
var body_scroll = $(window).scrollTop();
$(window).on('scroll', function(){
$(document).scrollTop(body_scroll);
});
},
close: function(){
$(window).off('scroll');
}
});