[英]How can I prevent the browser to scroll to the top on hash change?
我正在構建一個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>
我沒有更改JavaScript中的任何內容。 但是,在我的代碼中使用此功能后,在訪問該頁面時我發現了另一個問題。 網頁將自動滾動到頂部,從而禁止查看頁面的底部,同時也禁用了某些其他功能。
有趣的是,當我手動單擊刷新按鈕時,頁面未顯示此症狀。 我沒有得到引起此問題的原因。
看,我的基本要求是阻止用戶訪問上一頁。 如果有其他選擇,那也將受到歡迎。
請幫助我解決此問題。 提前致謝。
您基本上是每50毫秒重新加載一次頁面
window.location.href += "#";
window.location.href += "1";
由於當location.href屬性更改時瀏覽器會重新加載,因此您需要在重新加載后再次調用該方法。
因此,該網站每次都開始再次顯示在頂部。
您可能會在變量中生成哈希,然后將其用於比較。
我已經修改了代碼。 現在,它可以在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(); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.