Remember the location of the scrollbar when the page refreshes

  • 2020-03-30 03:22:54
  • OfStack

Remember the position of the scroll bar when clicking the button to refresh the page
 
<script type="text/javascript"> 
window.onbeforeunload = function () { 
var scrollPos; 
if (typeof window.pageYOffset != 'undefined') { 
scrollPos = window.pageYOffset; 
} 
else if (typeof document.compatMode != 'undefined' && 
document.compatMode != 'BackCompat') { 
scrollPos = document.documentElement.scrollTop; 
} 
else if (typeof document.body != 'undefined') { 
scrollPos = document.body.scrollTop; 
} 
document.cookie = "scrollTop=" + scrollPos; //Store the scrollbar location into cookies
} 

window.onload = function () { 
if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) { 
var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/); //If the cookie is not empty, the scrollbar position is read
document.documentElement.scrollTop = parseInt(arr[1]); 
document.body.scrollTop = parseInt(arr[1]); 
} 
} 
</script> 

Related articles: