刷新页面但使用倒数计时器保持滚动位置

Refresh Page but keep scoll position with countdown timer

所以我有这段代码可以在倒计时达到 0 后刷新页面。倒计时显示在底部的 div 中。

<script>
    (function countdown(remaining) {
    if(remaining === 0)
        location.reload(true);
    document.getElementById('countdown').innerHTML = remaining;
    setTimeout(function(){ countdown(remaining - 1); }, 1000);
})(60);
</script>

<span id="countdown" class="bold"></span>

我希望它以相同的方式刷新,但由于页面很长,因此保持浏览器上的滚动位置。使用此代码是否可行?

请举个例子,因为我不太理解javascript..

谢谢

您以前使用过localStorage 或cookies 吗?这些是用户浏览器的方便部分,您可以在其中实际存储和保存自定义数据位,仅供他们使用。有关详细信息,请参阅 localStorage API

无论如何,您可以使用 localStorage,然后当您的用户滚动时,您可以只存储他们向下滚动的距离。然后,在页面加载时,如果该 localStorage 键有值,则将用户向下滚动那么远。

我制作了一个片段,但遗憾的是,他们的片段 iframe 不允许我访问 localStorage 以实际向您展示它是如何工作的。但是,无论如何我确实在其中放了一些行(虽然未经测试)和一些评论来尝试帮助说明您可以如何去做的大致思路。

除此之外,您唯一可以做的就是进行测试,以确保他们的浏览器支持 localStorage,然后,如果不支持,您可以退回到尝试使用 cookie 或其他一些方法!

function updateScrollStuff() {
  // this tells us how far down we've scrolled as a number, like '476'
  var scrollPosition = $(document).scrollTop();
  
  // I cant access localStorage from the iframe they're using here, but I think this
  // would be what you'd want to do with it to store that scroll position
  // localStorage.storedScrollPosition = scrollPosition;

  // this line is just illustrative, showing you that the number for the scroll position is updating
  // every time you scroll - you don't need this for your final purposes
  $("#scroll-position").text(scrollPosition + "px");
}

// when the user scrolls, call that function above
$(window).scroll(function() {
  updateScrollStuff();
});

// I can't test it here, but on page load I would check to
// see if a value exists, and then scroll to it if it does!
$(window).load(function() {
  // again, with local storage blocked all I can do is show you what
  // it would look like
  // typeof 'undefined' is just a check you can make to see if a variable exists
  // if (typeof localStorage.storedScrollPosition != 'undefined') {
  //   $("html, body").scrollTop(localStorage.storedScrollPosition);
  // }
});
body, html {
  margin: 0;
  padding: 0;
}

.section {
  width: 100%;
  height: 200px;
}

#section-1 {
  background-color: #333333;
}

#section-2 {
  background-color: #666666;
}

#section-3 {
  background-color: #999999;
}

#section-4 {
  background-color: #aaaaaa;
}

#scroll-position {
  background-color: black;
  color: white;
  position: fixed;
  top: 0;
  left: 0;
  margin: 0;
  padding: 15px;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section-1" class="section"></div>
<div id="section-2" class="section"></div>
<div id="section-3" class="section"></div>
<div id="section-4" class="section"></div>
<h3 id="scroll-position">Scroll to see this change</h3>