Javascript 防止固定正文滚动到页面顶部

Javascript 防止固定正文滚动到页面顶部,javascript,Javascript,我有一个按钮,它可以防止默认设置并打开一个模式。我试图使模态背后的背景保持固定,然后在模态关闭时取消固定 我遇到的问题是,当我将背景设置为“已修复”时: if (modal.classList.contains('is-active')) { body.style.position = 'fixed'; } 背景中的页面滚动到顶部,当模式关闭时,用户不在他们离开的地方。为了改进用户体验,我希望用户返回到他们离开的地方,因此在我的函数中,我有: const scrollY = windo

我有一个按钮,它可以防止默认设置并打开一个模式。我试图使模态背后的背景保持固定,然后在模态关闭时取消固定

我遇到的问题是,当我将背景设置为“已修复”时:

if (modal.classList.contains('is-active')) {
    body.style.position = 'fixed';
}
背景中的页面滚动到顶部,当模式关闭时,用户不在他们离开的地方。为了改进用户体验,我希望用户返回到他们离开的地方,因此在我的函数中,我有:

const scrollY = window.pageYOffset;

if (modal.classList.contains('is-active')) {
    body.style.position = 'fixed';
} else {
    body.style.position = '';
    window.scrollTo(0, scrollY);
}
当用户单击按钮打开模式时,会触发上述代码

但是,由于功能在模式关闭时重新加载,并且主体位置“固定”已将滚动位置更改为0,这将覆盖
scrollY

因此,这可以通过以下两种方式之一解决:

a) 更新主体样式位置时,如何防止滚动位置更改为0,或

b) 如何保持
的值滚动?

我的建议是:

if (modal.classList.contains('is-active')) {
   body.classList.toggle('is-modal-open');
}
css的某个地方:

.is-modal-open {
      position: absolute;
      height: 100vh;
      width: 100vw;
      overflow: hidden;
}

不必将整个身体设置为固定位置,您可以改为对模态进行设置,只需在身体上设置
overflow:hidden
。这样就省去了在打开/关闭模式时存储和恢复滚动位置的麻烦

函数openModal(){
document.body.classList.add('show-modal');
}
函数hideModal(){
document.body.classList.remove('show-modal');
}
#模态{
位置:固定;
排名:0;
右:0;
底部:0;
左:0;
背景:rgba(0,0,0,0.33);
显示:无;
填充:3em;
}
body.show-modal{
溢出:隐藏;
}
body.show-modal#modal{
显示:块;
}
这是顶部…
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
长内容
开放模态 关闭modal
我的最终解决方案(感谢上面的答案让我走上了正确的道路,以及to的评论):

在我的函数之外,我声明了
var scrollY

// Locks the background and makes it not scrollable
if (modal.classList.contains('is-active')) {
    scrollY = window.pageYOffset;
    console.log("open " + scrollY);
    body.classList.toggle('popup-open--body');
} else {
    console.log("closed " + scrollY);
    body.classList.remove('popup-open--body');
    window.scrollTo(0, scrollY);
}
在我的CSS中:

.popup-open--body {
  overflow: initial;
  position: fixed;
  width: 100%;
}

每次显示模式时都需要设置scrollY,但关闭模式时不需要设置scrollY。@ConstantinGroß我也尝试过,因为它是在if语句中设置的,当它重新加载时,它说scrollY是未定义的。您是否尝试在外部范围中定义它,以便在内部函数中设置时保持定义状态?将高度设置为100vh会使我(Chrome,Ubuntu)在代码段上看起来不错,但不幸的是,这在我的项目中不起作用。我曾尝试在弹出窗口打开但背景仍可滚动时,将
overflow:hidden
添加到正文中。