英文:
Unable to freeze the scroll after setting body.overflow to hidden in Next Js
问题
I am having this issue in my Next.js where I am unable to freeze the page from scrolling even after I set the document.body.style.overflow
to hidden
.
As you can see:
In lines 11-14 where I click the freeze button, it disables scrolling.
enter image description here
Result:
The page is still scrollable.
Please let me know the solution to this.
英文:
I am having this issue in my Nextjs where I am unable to freeze the page from scrolling even after I set the document.body.style.overflow
to hidden
.
As you can see:
In lines 11-14 where I click the freeze button, it disables scrolling.
enter image description here
Result:
The page is still scrollable.
Please let me know the solution to this.
答案1
得分: 1
You need to add position:fixed
in addition to overflow:hidden
.
document.body.style.cssText = "overflow: hidden; position: fixed;";
Preventing scrolling will lose the scroll position. So, when scrolling is reenabled, it will reset the scroll position to the top of the page instead of where the user left off. To prevent this, you need to set the scrollTop position.
const scrollTop = (document.documentElement || document.body).scrollTop;
document.body.style.cssText = `overflow: hidden; position: fixed; margin-top: -${scrollTop}px;`;
On unfreezing, set the scroll top value to the original scroll top value before the freeze. Store it in state or a variable so it can be used later.
const scrollTop = (document.documentElement || document.body).scrollTop; // original value to store in state or variable before freezing.
// After unfreezing, set back to the original value
document.documentElement.scrollTop = scrollTop;
document.body.scrollTop = scrollTop;
英文:
You need to add position:fixed
in addition to overflow:hidden
document.body.style.cssText = "overflow: hidden; position:fixed;";
Preventing scrolling will lose the scroll position. So, when scrolling is reenabled, it will reset the scroll position to the top of the page instead of where the user left off. To prevent this, you need to set the scrollTop position.
const scrollTop = (document.documentElement || document.body).scrollTop;
document.body.style.cssText = `overflow: hidden; position:fixed; margin-top: -${scrollTop}px;`; // add here to prevent shifting content on freeze
On unfreezing, set the scroll top value to the original scroll top value before the freeze. Store it in state or a variable so it can be used later.
const scrollTop = (document.documentElement || document.body).scrollTop; // original value to store in state or variable before freezing.
//After unfreezing, set back to original value
document.documentElement.scrollTop = scrollTop;
document.body.scrollTop = scrollTop;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论