解析 Page.MaintainScrollPositionOnPostBack 属性

ASP.NET 的页面执行 PostBack 动作时,页面由伺服端重新传给客户端,而页面的垂直滚动条会跳回最上方,水平滚动条会跳回最左方。
 为了解决此情形,只要将 Page 的MaintainScrollPositionOnPostBack 属性设为True 时,页面就会自动维护滚动条位置,它是如何实现这个动作的呢?
 
当把 Page.MaintainScrollPositionOnPostBack = "True" 时,检视 HTML 原始码,可以发现它多了"__SCROLLPOSITIONX" 及"__SCROLLPOSITIONY" 这二个 HiddenField,这二个 HiddenField 主要是要来记录页面滚动条的水平及垂直位置。
 

<input type="hidden" name="__SCROLLPOSITIONX" id="__SCROLLPOSITIONX" value="0" />
<input type="hidden" name="__SCROLLPOSITIONY" id="__SCROLLPOSITIONY" value="204" />


页面上也会多了以下这些JavaScript 程序代码,它主要是透过WebForm_SaveScrollPositionSubmit 及WebForm_RestoreScrollPosition 这二个函式来维护页面滚动条位置。

 <script type="text/javascript">
 <!--
 theForm.oldSubmit = theForm.submit;
 theForm.submit = WebForm_SaveScrollPositionSubmit;
 
 theForm.oldOnSubmit = theForm.onsubmit;
 theForm.onsubmit = WebForm_SaveScrollPositionOnSubmit;
 
 theForm.oldOnLoad = window.onload;
 window.onload = WebForm_RestoreScrollPosition;
 // -->
 </script>
 


当页面Submit 时会利用WebForm_SaveScrollPositionSubmit 函式来记录页面目前的水平及垂直滚动条位置,将水平滚动条位置记录于"__SCROLLPOSITIONX" 这个 HiddenField,垂直滚动条位置记录于"__SCROLLPOSITIONY" 这个 HiddenField。
 
而 PostBack 后页面重新加载后,会利用WebForm_RestoreScrollPosition 函式来回复页面滚动条位置,也就是将记录在"__SCROLLPOSITIONX" 及"__SCROLLPOSITIONY" 这二个 HiddenField 的值,重新设定页面的水平及垂直滚动条位置,如此就达到维护页面滚动条位置的动作了。

转载地址:http://www.cnblogs.com/jeff377/archive/2008/01/17/1042228.html

猜你喜欢

转载自blog.csdn.net/aaron_luchen/article/details/8662208