简体   繁体   English

window.scrollTo 方法并非每次都有效 - JavaScript

[英]window.scrollTo method doesn't work everytime - JavaScript

I am working on a website feature that stores the user scroll position ( window.pageYOffset ) into a cookie and scrolls to it whenever the user is redirected to another link so user can continue where he left off.我正在开发一个网站功能,它将用户滚动 position ( window.pageYOffset ) 存储到 cookie 中,并在用户被重定向到另一个链接时滚动到它,这样用户就可以从他离开的地方继续。

Using a window.scrollTo method, however, works only sometimes.但是,使用window.scrollTo方法仅在某些时候有效。 I was trying to put it in window.onload as well as in JQuery's $(document).ready() events, it mostly scrolls succesfully to desired position, but sometimes it just scrolls all the way to the top for no reason at all.我试图把它放在window.onload以及 JQuery 的$(document).ready()事件中,它大多成功地滚动到所需的 position,但有时它只是无缘无故地一直滚动到顶部。

Note that the cookie is updated with window.onscroll method, which may not be the best practice and the problem may be caused by that.请注意,cookie 是使用window.onscroll方法更新的,这可能不是最佳实践,问题可能是由此引起的。

Current code:当前代码:

try {
   window.scrollTo(parseInt(getCookie("scrollY")), 0);
} catch (err) {
   console.log("Couldn't scroll");
}

window.onscroll = () => {
   document.cookie = "scrollY=" + Math.round(window.pageYOffset);
};

I am working on a website feature that stores the user scroll position ( window.pageYOffset ) into a cookie and scrolls to it whenever the user is redirected to another link so user can continue where he left off.我正在开发一个网站功能,它将用户滚动 position ( window.pageYOffset ) 存储到 cookie 中,并在用户被重定向到另一个链接时滚动到它,这样用户就可以从他离开的地方继续。

Using a window.scrollTo method, however, works only sometimes.但是,使用window.scrollTo方法仅在某些时候有效。 I was trying to put it in window.onload as well as in JQuery's $(document).ready() events, it mostly scrolls succesfully to desired position, but sometimes it just scrolls all the way to the top for no reason at all.我试图把它放在window.onload以及 JQuery 的$(document).ready()事件中,它大多成功地滚动到所需的 position,但有时它只是无缘无故地一直滚动到顶部。

Note that the cookie is updated with window.onscroll method, which may not be the best practice and the problem may be caused by that.请注意,cookie 是使用window.onscroll方法更新的,这可能不是最佳实践,问题可能是由此引起的。

Current code:当前代码:

try {
   window.scrollTo(parseInt(getCookie("scrollY")), 0);
} catch (err) {
   console.log("Couldn't scroll");
}

window.onscroll = () => {
   document.cookie = "scrollY=" + Math.round(window.pageYOffset);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM