ASP.NET 2.0 had the followin开发者_JS百科g property MaintainScrollPositionOnPostBack and it could be used to maintain browser position on post back. Can this be achieved using jQuery and if yes how? I have read a few articles mentioning that MaintainScrollPositionOnPostBack doesnt work in some browsers like Chrome/Safari etc.
Create an ASP hidden input field to store the position across postbacks, pass the ClientID of that field into the code below:
// client id of the hidden input field
var hiddenInputId = '<%= _myHiddenInputField.ClientID %>';
// store the current scroll position into the input
function storeScrollPosition(){
$('#'+hiddenInputId)[0].value = scrollPosition();
}
// load the value out of the input and scroll the page
function loadScrollPosition(){
var curPosition = $('#'+hiddenInputId)[0].value;
if (curPosition > 0)
$(window).scroll(curPosition);
}
// determine the scroll position (cross browser code)
function scrollPosition() {
var n_result = window.pageYOffset ?
window.pageYOffset : 0;
var n_docel = document.documentElement ?
document.documentElement.scrollTop : 0;
var n_body = document.body ?
document.body.scrollTop : 0;
if (n_docel && (!n_result || (n_result > n_docel)))
n_result = n_docel;
return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
// on load of the page, load the previous scroll position
$(document).ready(function(){loadScrollPosition();});
// on scroll of the page, update the input field
$(window).scroll(function(){storeScrollPosition();});
This will only work for postbacks. If you need to always have the same screen position we can play with cookies :)
精彩评论