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

≡放荡痞女 提交于 2019-12-13 21:22:44

问题


I am building a web application where I need to prevent back navigation in the browser history. After searching the threads in StackOverflow I found this:

<!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>

Reference Disable browser's back button

I did not change anything in the JavaScript. However, after using this in my code, I am observing another problem while the page is being visited. The webpage is getting auto-scrolled to the top prohibiting viewing the bottom part of the page alongwith disabling of some other features also.

The interesting part is that the page is not showing this symptom when I manually hit the refresh button. I am not getting what is causing this issue.

See, my basic requirement is to stop users visiting the previous page. If any other alternative is there, that would also be welcome.

Please help me to fix this. Thanks in advance.


回答1:


I have modified code. Now its works in all modern browsers, IE8 and above

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:


You are basically reloading the page every 50 ms through

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

Since the browser reloads when the location.href attribute changes.And you call that method again after that reload.

So the site starts to display at the top again every time.

You might generate the hash within a variable and use that for comparison i guess.



来源:https://stackoverflow.com/questions/29590041/how-can-i-prevent-the-browser-to-scroll-to-the-top-on-hash-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!