How to avoid scrolling to the top of the page when emptying window.location.hash
Why does the following code make the scroll jump to the top of the page?
window.开发者_StackOverflow中文版location.hash = ''
Is there a way to empty it without jumping to the top of the page?
window.location.hash
keeps track of the current anchor position on the page. When you set it to be an anchor, the page will automatically go to that anchor. When you remove it, the page will go to 'blank' which is the top of the page!
To get around this do the following:
var scrollPosition = window.style.scrollTop;
window.location.hash = '';
window.style.scrollTop = scrollPosition;
I came across this behaviour when a bug appeared in code I had written that was on a setInterval watching the hash.
setInterval(function(){
var match = hash.match(/myValue=([^&]+)/);
window.location.hash = '';
if (match && match.length == 2) {
$('#myDiv').val(match[1]);
// RUN CODE
}
}, 250);
In Chrome this code causes no problems, but in Internet Explorer and Firefox it will not let you scroll as it is always trying to scroll to the top of the page.
Of course the above code is "wrong" anyway as the clearing of the hash should only happen if a match is found. Sadly I only found this bug after checking in Firefox.
精彩评论