有時候選擇下拉框自動postback時,由於頁面太長,postback後頁面自動滾動到最上面,不能保持postback之前的位置,如果在Page_Load調用下面的方法就可以解決這個問題:
/**//// <summary>
/// Persist ScrollBar's Position After a PostBack
/// </summary>
private void PersistScrollPosition()
{
System.Text.StringBuilder saveScrollPosition = new System.Text.StringBuilder();
System.Text.StringBuilder setScrollPosition = new System.Text.StringBuilder();
Page.RegisterHiddenField("__SCROLLPOS", "0");
saveScrollPosition.Append("<script language='javascript'>");
saveScrollPosition.Append("function saveScrollPosition() {");
saveScrollPosition.Append(" document.forms[0].__SCROLLPOS.value = document.body.scrollTop;");
saveScrollPosition.Append("}");
saveScrollPosition.Append("document.body.onscroll=saveScrollPosition;");
saveScrollPosition.Append("</script>");
Page.RegisterStartupScript("saveScroll", saveScrollPosition.ToString());
if (Page.IsPostBack)
{
setScrollPosition.Append("<script language='javascript'>");
setScrollPosition.Append("function setScrollPosition() {");
setScrollPosition.Append(" document.body.scrollTop = " + Request["__SCROLLPOS"] + ";");
setScrollPosition.Append("}");
setScrollPosition.Append("document.body.onload=setScrollPosition;");
setScrollPosition.Append("</script>");
Page.RegisterStartupScript("setScroll", setScrollPosition.ToString());
}
}
跳到指定位置:public void MoveTo(string name)
{
System.Text.StringBuilder sbScript = new System.Text.StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append("document.location = '" + name + "';\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");
Page.RegisterClientScriptBlock("MoveToNext", sbScript.ToString());
}
設定焦點到指定控制項:
public static void SetFocus(System.Web.UI.Page Page,System.Web.UI.Control control)
{
StringBuilder sb = new StringBuilder();
sb.Append("\r\n<script language='JavaScript'>\r\n");
sb.Append("<!--\r\n");
sb.Append("function SetFocus()\r\n");
sb.Append("{\r\n");
sb.Append("\tdocument.");
System.Web.UI.Control p = control.Parent;
while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;
sb.Append(p.ClientID);
sb.Append("['");
sb.Append(control.UniqueID);
sb.Append("'].focus();\r\n");
sb.Append("}\r\n");
sb.Append("window.onload = SetFocus;\r\n");
sb.Append("// -->\r\n");
sb.Append("</script>");
control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
}