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

时间:2015-04-12 13:35:00

标签: javascript html browser-history

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

有趣的是,当我手动点击刷新按钮时,页面没有显示此症状。我没有得到导致这个问题的原因。

请参阅,我的基本要求是阻止用户访问上一页。如果有任何其他选择,那也是受欢迎的。

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

2 个答案:

答案 0 :(得分:1)

您基本上每50毫秒通过

重新加载页面
window.location.href += "#";
window.location.href += "1";

由于当location.href属性发生变化时浏览器会重新加载。在重新加载后再次调用该方法。

因此,网站每次都会再次显示在顶部。

您可以在变量中生成散列,并将其用于比较我猜。

答案 1 :(得分: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(); });
相关问题