【问题标题】:How can I prevent the browser to scroll to the top on hash change?如何防止浏览器在哈希更改时滚动到顶部?
【发布时间】:2015-04-12 13:35:00
【问题描述】:

我正在构建一个 Web 应用程序,我需要在其中防止浏览器历史记录中的后退导航。在 StackOverflow 中搜索线程后,我发现:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
     window.location.href += "#";
     setTimeout("changeHashAgain()", "50"); 
}

function changeHashAgain() {
  window.location.href += "1";
}

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
         window.location.hash = storedHash;
    }
}, 50);
</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>

参考Disable browser's back button

我没有更改 JavaScript 中的任何内容。但是,在我的代码中使用它之后,我在访问页面时发现了另一个问题。网页自动滚动到顶部,禁止查看页面底部,同时还禁用了一些其他功能。

有趣的是,当我手动点击刷新按钮时,页面没有显示此症状。我不知道是什么导致了这个问题。

看,我的基本要求是阻止用户访问前一页。如果有任何其他选择,那也将受到欢迎。

请帮我解决这个问题。提前致谢。

【问题讨论】:

  • 由于 Javascript 在客户端运行,如果他们愿意,他们可以实时编辑您的脚本,您无法有效地阻止用户使用浏览器的内置功能。

标签: javascript html browser-history


【解决方案1】:

我修改了代码。现在它适用于所有现代浏览器,IE8 及更高版本

var storedHash = window.location.hash;
function changeHashOnLoad() {
    window.location.href += "#";
    setTimeout("changeHashAgain()", "50");
}

function changeHashAgain() {
    window.location.href += "1";
}

function restoreHash() {
    if (window.location.hash != storedHash) {
        window.location.hash = storedHash;
    }
}

if (window.addEventListener) {
    window.addEventListener("hashchange", function () {
        restoreHash();
    }, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", function () {
        restoreHash();
    });
}
$(window).load(function () { changeHashOnLoad(); });

【讨论】:

    【解决方案2】:

    您基本上每 50 毫秒重新加载一次页面

    window.location.href += "#";
    window.location.href += "1";
    

    由于 location.href 属性更改时浏览器会重新加载。并且您在重新加载后再次调用该方法。

    所以网站每次都重新开始显示在顶部。

    您可能会在变量中生成哈希值并使用它进行比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多