【问题标题】:What's the best practice to have browser reset scroll position on page refresh?让浏览器在页面刷新时重置滚动位置的最佳做法是什么?
【发布时间】:2018-03-20 02:06:36
【问题描述】:

问题

我正在创建一个相当简单的投资组合。我在顶部有一个导航栏,有几个导航链接。其中之一是“About Me”,点击后会自动提示页面跳转到html div section标签,元素id为#about-me。 URL 也会发生变化,并在末尾附加 #about-me

当我刷新页面时,url 保持不变,因此页面不会滚动回顶部,而是在重新加载时显示相同的位置。我相信这是由于浏览器自动使用缓存? (如果我错了请纠正我)

妥善处理的最佳方法是什么?

一些可能的解决方案

  1. 当 DOM 完成加载并准备好进行操作时,使用 jQuery .ready() 函数立即调用一个函数,该函数将自动将 window.location.href 设置为源 URL,这将重置滚动位置。

  2. 防止浏览器缓存。 (我想这有一个缺点,特别是如果我希望我网站的其他部分在以后使用缓存?)

【问题讨论】:

  • 尝试在加载时使用 scrollTop:0
  • 将滚动位置保存到localStorage并在页面刷新时访问
  • 此行为被妥善处理,与缓存无关。 #about-me 被称为锚点,当提供浏览器时,设计会将页面滚动到它。
  • @lolbas 谢谢,我知道这是正确的行为,但是,我的印象是页面刷新会重新加载整个 DOM(包括样式表和脚本),因此,从原始网址。但是,页面刷新从原始 url 开始,并附加了我的页面最后滚动到的部分的 id。是否应该在页面刷新时不重置 URL?抱歉,如果我让这变得混乱。
  • 我建议您将问题改为询问“如何”,而不是询问“最佳实践”或“最佳方式”。最佳实践问题会邀请基于意见的答案,因此可能会被关闭。

标签: javascript jquery html css


【解决方案1】:

所以我找到了一个非常简单的答案,以防有人想知道。阻止事件的默认行为将阻止 url 在末尾添加哈希,然后您必须添加代码才能使滚动正常工作,因为阻止默认行为也会阻止导航链接正常工作。但是在页面刷新时,页面将从顶部开始,只要您省略在 animate 函数末尾添加哈希即可。

来自W3schools

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Just omit this line of code to in order to have page refresh 
        //start at the top of the page
        window.location.hash = hash;
      });
    } // End if
  });
});
</script>
 <style>
body, html, .main {
    height: 100%;
}

section {
    min-height: 100%;
}
</style>
</head>
<body>

<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>

<div class="main">
  <section></section>
</div>

<div class="main" id="section2">
  <section style="background-color:blue"></section>
</div>

</body>
</html>

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2013-09-08
    • 2021-10-04
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多