【问题标题】:how to make the page not reload after changing the hash? [duplicate]更改哈希后如何使页面不重新加载? [复制]
【发布时间】:2014-09-23 10:33:13
【问题描述】:
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <button onclick="clickHash()">hash</button>
        <button onclick="clickCancel()">cancel</button>
        <div style="height: 2000px; width: 1000px; background: red;"></div>
        <button onclick="clickCancel()">cancel</button>
        <script>
            clickHash = function(){
                location.hash = "#test";
                window.scrollTo(0, 2000);
            }
            clickCancel = function(){
                location.hash = "";
            }
            handler = function() {
              console.log("hashchange fired");
            }
            window.onhashchange = handler;
        </script>
    </body>
</html>

我对上面代码的期望是,当我单击哈希按钮时,更改哈希并将页面滚动到底部,当我单击取消按钮时,删除哈希。但是,当哈希被删除时,页面将跳转到顶部。我猜这可能是因为当哈希发生变化时页面会重新加载或刷新。

有谁知道如何在更改哈希后使页面不重新加载?

Here 就是一个例子。

【问题讨论】:

  • 请问您为什么要删除哈希?
  • @isherwood 谢谢你的回答。我会检查它是否适合我。
  • @kaspermoerch 在我的应用程序中,我使用哈希来确定图片是否可见。另外,我必须设置一个按钮来设置哈希为空,这意味着没有图片显示。

标签: javascript


【解决方案1】:

页面不会重新加载。你正在设置一个新的哈希"",它相当于"top of the page",所以浏览器会按照你告诉他的去做:跳到顶部。

如果你想保住这个位置,你应该记得scrollTo()

clickCancel = function(){
  location.hash = "";
  window.scrollTo(0, 2000);
}

【讨论】:

  • "" 相当于“页面顶部”是有意义的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-08-11
  • 2012-07-28
  • 1970-01-01
  • 2012-06-23
  • 2011-03-21
  • 2010-12-08
相关资源
最近更新 更多