按下后退按钮时如何保留可滚动区域的滚动位置? [英] How can I retain the scroll position of a scrollable area when pressing back button?

查看:28
本文介绍了按下后退按钮时如何保留可滚动区域的滚动位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个大的可滚动 div 中有很长的链接列表.每次当用户单击链接然后单击后退按钮时,它都会从 div 的最顶部开始.它对我们的用户来说不是用户友好的.有什么方法可以让浏览器在按下后退按钮时滚动到上一个位置?

I have a long list of links inside a big scrollable div. Each time when a user click on a link then click the back button, it starts at the very top of the div. It is not user friendly to our users. Any ways to let the browser scroll to the previous position when pressing the back button?

非常感谢!

推荐答案

在页面卸载期间,获取滚动位置并将其存储在本地存储中.然后在页面加载期间,检查本地存储并设置滚动位置.假设您有一个 ID 为 element 的 div 元素.如果是页面,请更改选择器:)

During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position. Assuming you have a div element with id element. In case it's for the page, please change the selector :)

$(function() {
   $(window).unload(function() {
      var scrollPosition = $("div#element").scrollTop();
      localStorage.setItem("scrollPosition", scrollPosition);
   });
   if(localStorage.scrollPosition) {
      $("div#element").scrollTop(localStorage.getItem("scrollPosition"));
   }
});

这篇关于按下后退按钮时如何保留可滚动区域的滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆