保存页面的滚动条的位置

1/// <summary>
 2        /// 功能:在页面post时保存屏幕滚动状态;
 3        /// 直接在Page_Load中加入Zeda.CNE.Common.RetainScrollPosition();
 4        /// 不能加在if(!Page.IsPostBack){}内;
 5        /// 加入的两个隐藏域为__SCROLLPOS_TOP和__SCROLLPOS_LEFT
 6        /// </summary>

 7        public static void RetainScrollPosition()
 8        {
 9            
10            System.Web.UI.Page page=(Page)HttpContext.Current.Handler;
11
12            page.RegisterHiddenField("__SCROLLPOS_TOP","0");
13            page.RegisterHiddenField("__SCROLLPOS_LEFT","0");
14                
15            string saveScrollPosition = "<script language='javascript'>function saveScrollPosition() {{document.forms[0].__SCROLLPOS_TOP.value = {0}.scrollTop;document.forms[0].__SCROLLPOS_LEFT.value = {0}.scrollLeft ;}}{0}.onscroll=saveScrollPosition;</script>";
16            string setScrollPosition = "<script language='javascript'>function setScrollPosition() {{{0}.scrollTop ='{1}';{0}.scrollLeft  ='{2}' }}{0}.onload=setScrollPosition;</script>";
17            
18            page.RegisterStartupScript("saveScroll"string.Format(saveScrollPosition,"window.document.body"));
19
20            if (page.IsPostBack)
21            {
22
23                page.RegisterStartupScript("setScroll"string.Format(setScrollPosition,"window.document.body", page.Request.Form["__SCROLLPOS_TOP"],page.Request.Form["__SCROLLPOS_LEFT"]));
24            }

25        }
原文地址:https://www.cnblogs.com/ghd258/p/270444.html