几年前做ASP.NET项目时,曾经遇到过修改DataList行时,页面回传后,不能恢复到原来的位置。经参考网上搜索的一段VB代码,改写成C#,解决了问题,并在以后的项目中多次应用。最近进行了改进,使其能恢复垂直和水平滚动条的位置,该方法也应用于其他与该应用类似的页面。
public
static
void
RetainScrollPosition()
... {
Page _page =(Page)HttpContext.Current.Handler;
StringBuilder ScrollPosition = new StringBuilder();
_page.RegisterHiddenField("__SCROLLTOP", "0");
_page.RegisterHiddenField("__SCROLLLEFT", "0");
ScrollPosition.Append("<SCRIPT LANGUAGE="JavaScript"> <!-- ");
ScrollPosition.Append(" function saveScrollPosition() { ");
ScrollPosition.Append(" document.forms[0].__SCROLLTOP.value = document.body.scrollTop;");
ScrollPosition.Append(" document.forms[0].__SCROLLLEFT.value = document.body.scrollLeft;");
ScrollPosition.Append(" } document.body.οnscrοll=saveScrollPosition; ");
if ( _page.IsPostBack )
...{
ScrollPosition.Append(" function setScrollPosition() { ");
ScrollPosition.AppendFormat(" document.body.scrollTop = {0}; ", _page.Request["__SCROLLTOP"]);
ScrollPosition.AppendFormat(" document.body.scrollLeft = {0}; ", _page.Request["__SCROLLLEFT"]);
ScrollPosition.Append(" } document.body.οnlοad=setScrollPosition; ");
}
ScrollPosition.Append("//--> <"+"/SCRIPT>");
_page.RegisterStartupScript("jsRetainScrollPosition", ScrollPosition.ToString());
}
... {
Page _page =(Page)HttpContext.Current.Handler;
StringBuilder ScrollPosition = new StringBuilder();
_page.RegisterHiddenField("__SCROLLTOP", "0");
_page.RegisterHiddenField("__SCROLLLEFT", "0");
ScrollPosition.Append("<SCRIPT LANGUAGE="JavaScript"> <!-- ");
ScrollPosition.Append(" function saveScrollPosition() { ");
ScrollPosition.Append(" document.forms[0].__SCROLLTOP.value = document.body.scrollTop;");
ScrollPosition.Append(" document.forms[0].__SCROLLLEFT.value = document.body.scrollLeft;");
ScrollPosition.Append(" } document.body.οnscrοll=saveScrollPosition; ");
if ( _page.IsPostBack )
...{
ScrollPosition.Append(" function setScrollPosition() { ");
ScrollPosition.AppendFormat(" document.body.scrollTop = {0}; ", _page.Request["__SCROLLTOP"]);
ScrollPosition.AppendFormat(" document.body.scrollLeft = {0}; ", _page.Request["__SCROLLLEFT"]);
ScrollPosition.Append(" } document.body.οnlοad=setScrollPosition; ");
}
ScrollPosition.Append("//--> <"+"/SCRIPT>");
_page.RegisterStartupScript("jsRetainScrollPosition", ScrollPosition.ToString());
}
调用方法:
在Page_Load事件中加上
RetainScrollPosition();