最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to refresh code without losing scroll position? - Stack Overflow

programmeradmin1浏览0评论

I am using the script to reload the page every 10 seconds. I want to retain the scroll position even after the refresh. The following is my script:

<script type="text/javascript" language="javascript">
  var idleInterval = setInterval("reloadPage()", 10000);

  function reloadPage() {
    location.reload(false);
  }
</script>

I am using the script to reload the page every 10 seconds. I want to retain the scroll position even after the refresh. The following is my script:

<script type="text/javascript" language="javascript">
  var idleInterval = setInterval("reloadPage()", 10000);

  function reloadPage() {
    location.reload(false);
  }
</script>

Share Improve this question edited Mar 1, 2019 at 4:56 MarredCheese 20.9k12 gold badges107 silver badges103 bronze badges asked Apr 16, 2018 at 11:41 Shrikant KumbharShrikant Kumbhar 291 gold badge1 silver badge5 bronze badges 1
  • 1 There is no need for an interval since this will only run once. Also, the fact that you need to refresh the page every x seconds sounds like bad design of a function that could be done with ajax. – Phiter Commented Apr 16, 2018 at 11:43
Add a ment  | 

3 Answers 3

Reset to default 10

you can do something like this :

window.addEventListener('scroll',function() {
    //When scroll change, you save it on localStorage.
    localStorage.setItem('scrollPosition',window.scrollY);
},false);

then on load :

window.addEventListener('load',function() {
    if(localStorage.getItem('scrollPosition') !== null)
       window.scrollTo(0, localStorage.getItem('scrollPosition'));
},false);

You can use session storage to store the position then get back to the position when the page is reloaded, like this:

$(window).scroll(function() {
  sessionStorage.scrollTop = $(this).scrollTop();
});

$(document).ready(function() {
  if (sessionStorage.scrollTop != "undefined") {
    $(window).scrollTop(sessionStorage.scrollTop);
  }
});

You can store the position on the user's localStorage before reloading and getting it when you open the page.

window.scrollTo(localStorage.scrollPos || 0, 0);

setTimeout(function(){
  //Saves the current scroll position before reloading the page.
  localStorage.setItem('scrollPos', window.pageYOffset || document.documentElement.scrollTop);
  location.reload();
}, 3000);

发布评论

评论列表(0)

  1. 暂无评论