如何防止浏览器在哈希更改时滚动到顶部?

How can I prevent the browser to scroll to the top on hash change?

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

<!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 中的任何内容。但是,在我的代码中使用它之后,我在访问页面时观察到另一个问题。该网页会自动滚动到顶部,禁止查看页面底部,同时也会禁用其他一些功能。

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

看,我的基本要求是阻止用户访问上一页。如果还有其他选择,那也欢迎。

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

通过

,您基本上每 50 毫秒重新加载一次页面
window.location.href += "#";
window.location.href += "1";

由于浏览器在 location.href 属性 changes.And 时重新加载,您在重新加载后再次调用该方法。

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

我猜你可能会在一个变量中生成散列并用它来进行比较。

我修改了代码。现在它适用于所有现代浏览器,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(); });