防止页面滚动

这个想必是大家经常遇到的,嘿嘿,估计大家会想要吧。

当页面postback以后,浏览的位置就跑到页面的顶部了,如果是一个很长的页面,客户就要拖来拖去,很不方便,下面是一个方法,可以记录浏览页面的位置,postback以后用script调整回去,

         #region 防止页面滚动 
        
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());
            }

        }

        
#endregion
 

使用方法:

body的ID改成mybody,page_load里头加上   RetainScrollPosition();

你可能感兴趣的:(滚动)