25
Views
4
Comments
scrollTop / scrollTo not working inside JS component on page load
Question
Application Type
Reactive

大家好,


我实现了一项功能,在用户离开之前将页面的当前滚动位置保存到 localStorage 中。当用户返回该页面时,我希望通过从 localStorage 读取值并相应地滚动页面来恢复滚动位置。


当我在浏览器控制台中使用 scrollTop 或 scrollTo 手动测试时,效果很好。然而,当我尝试在 JavaScript 组件中(例如,在页面加载时运行的脚本中)执行相同操作时,它似乎完全不起作用——页面仍然停留在顶部。


有人遇到过这个问题吗?知道为什么滚动功能在控制台中有效,但在脚本中无效吗?


任何帮助都值得感激 — — 提前致谢!

2023-06-13 12-29-43
Sakthivel P

Hi @QIANGQIANG XIE,

The scrollTop/scrollTo call inside your OnReady JavaScript is likely executing before the DOM is fully rendered or the element is visible. You can use either

requestAnimationFrame (Preferred)

OR

setTimeout

UserImage.jpg
QIANGQIANG XIE

Recently, I came across an explanation that seems to shed some light on the issue. The element I'm trying to scroll has a very long block of text, so the browser needs time to calculate its exact height. If scrollTop or scrollTo is called before that layout calculation is complete, it doesn’t seem to take effect.

To test this, I used a delayed function with a longer timeout (2 seconds), and surprisingly — it worked! The scroll position was correctly applied after the full content height had been resolved.

Thanks again for your insights .

2024-07-12 05-57-50
Gourav Shrivastava
Champion

Hello @QIANGQIANG XIE,

Follow these steps 

Before leaving the page ( OnDestroy), save the window.scrollY in local storage 

like:-  localStorage.setItem('screen-name', window.scrollY);

With your screen name and if you came again on the same screen use this code on ready event of the screen

  1.   const scrollY = localStorage.getItem('screen-name ');
  2.   if (scrollY) {
  3.     setTimeout(() => {
  4.       window.scrollTo(0, parseInt(scrollY));
  5.     }, 100); 
  6.   }

It take some time and scroll the view 

Thanks

Regards,

Gourav Shrivastava

 

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.