将新页面滚动到相同的页面滚动位置

New page to same page scroll position

本文关键字:滚动 位置 新页面      更新时间:2023-09-26

对于打开新页面的链接$("#english"),我使用下面的代码使新页面转到与上一页面(其中包含链接)相同的页面滚动位置。

if(localStorage.getItem('scroll'))  
    {
        window.scrollTo(0, parseInt(localStorage.getItem("scroll")));
    }

        $("#english").on("click",function()
        {
             localStorage.setItem("scroll", document.body.scrollTop);
        });
window.localStorage.clear();

使用Safari作为浏览器效果很好,但使用FireFox时,新页面从页面顶部开始,不会转到相同的页面滚动位置。有人吗?我如何使这个跨浏览器验证?

原因是firefox为document.body.scrollTop返回0
相反,Firefox希望您使用document.documentElement.scrollTop,但它不适用于Safari。

有许多可能的属性在某些浏览器中有效,而在其他浏览器中无效。

根据我的经验,window.pageYOffset效果最好(IE>=9)

所以这是有效的代码(感谢Jayms):

<script>
/*makes a new page jump to same scroll position as the scroll position when the link is activated*/ 
if(localStorage.getItem('scroll'))  
        {
            window.scrollTo(0, parseInt(localStorage.getItem("scroll")));
        }
$("#englishflag").on("click",function()
{
     localStorage.setItem("scroll", window.pageYOffset);
});

 window.localStorage.clear();
  /*END*/ 
</script>