asp.net|頁面
一、
private void RetainScrollPosition()
{
StringBuilder saveScrollPosition = new StringBuilder ();
StringBuilder setScrollPosition = new StringBuilder ();
RegisterHiddenField("__SCROLLPOS", "0");
saveScrollPosition.Append("<script language='javascript'>");
saveScrollPosition.Append("function saveScrollPosition() {");
saveScrollPosition.Append(" document.forms[0].__SCROLLPOS.value = MyBody.scrollTop;");
saveScrollPosition.Append("}");
saveScrollPosition.Append("MyBody.onscroll=saveScrollPosition;");
saveScrollPosition.Append("</script>");
RegisterStartupScript("saveScroll", saveScrollPosition.ToString());
if (Page.IsPostBack)
{
setScrollPosition.Append("<script language='javascript'>");
setScrollPosition.Append("function setScrollPosition() {");
setScrollPosition.Append(" MyBody.scrollTop = " + Request["__SCROLLPOS"] + ";");
setScrollPosition.Append("}");
setScrollPosition.Append("MyBody.onload=setScrollPosition;");
setScrollPosition.Append("</script>");
RegisterStartupScript("setScroll", setScrollPosition.ToString());
}
}
page_load 時,執行RetainScrollPosition()
頁面html中,body加id=MyBody,即可這樣一次添加,只要繼承的頁面都會實現你想要的了
(引用別人的,原作者我忘了,在此感謝)
二、
在你需要的位置添加一個對象控制項,讓頁面重新整理後定位到此控制項的位置,使用了scrollIntoView方法。
public void ScrollToObject(string str_Ctl_Name,Page page)
{
if(!page.IsStartupScriptRegistered ("ScrollObject"))
{
page.RegisterStartupScript("msgScrollObject"," <script>document.forms(0)."+str_Ctl_Name+".scrollIntoView();document.forms(0)."+str_Ctl_Name+".focus(); </script>");
}
}
註:ScrollToObject:方法名
str_Ctl_Name:控制項名