Vb.net保持页面滚动条位置不变的实现代码

发布时间:2019-08-11编辑:脚本学堂
在ASP.net中如何保持页面中滚动条的位置,使得页面提交后还在原来的位置呢,这需要对页面中DIV等进行控制,本文给出的代码很好的实现了这一点。

我们知道,在控制浏览器滚动条大多用Page.SmartNavigation = False,对于页面中DIV滚动条控制也是如此,具体应用参考如下的代码吧。

//代码1
Public Shared Sub SaveDivScrollPosition(ByVal divIDArray As String, ByVal objPage As Page)
Dim saveScrollPosition As String
Dim i As Integer
Dim divID() As String
divID = divIDArray.Split(",")
For i = 0 To divID.Length - 1
objPage.RegisterHiddenField(divID(i) & "__SCROLLPOS", objPage.Request.Form(divID(i) & "__SCROLLPOS"))
saveScrollPosition = "<script language='javascript'>" _
& "function saveScrollPosition() {" _
& " if (document.all['" & divID(i) & "'] != undefined) {" _
& "document.forms[0]." & divID(i) & "__SCROLLPOS.value = " _
& "document.all['" & divID(i) & "'].scrollTop + ',' " _
& " + document.all['" & divID(i) & "'].scrollLeft;}}" _
& "if (document.all['" & divID(i) & "'] != undefined) {document.all['" & divID(i) & "'].onscroll=saveScrollPosition;}" _
& "</script>"
objPage.RegisterStartupScript("saveScroll" & divID(i), saveScrollPosition)
Next
End Sub

//代码2
Public Shared Sub RestoreDivScrollPosition(ByVal divIDArray As String, ByVal objPage As Page)
Dim restoreScrollPosition As String
Dim setPositionFunction As String
Dim i As Integer
Dim divID() As String
divID = divIDArray.Split(",")
For i = 0 To divID.Length - 1
setPositionFunction = setPositionFunction & "SetScrollPosition('" & divID(i) & "');"
Next
restoreScrollPosition = "<script language='javascript'>" _
& setPositionFunction _
& "</script>"
objPage.RegisterStartupScript("restoreScroll", restoreScrollPosition)
End Sub

JAVASCRIPT:
function SetScrollPosition(divID){
var e;
var a;
var obj;
if (document.getElementById(divID)){
obj = eval('document.forms[0].' + divID + '__SCROLLPOS');
if (obj) {
e=eval('document.forms[0].' + divID + '__SCROLLPOS').value;
a=e.split(',');
document.getElementById(divID).scrollTop= a[0];
document.getElementById(divID).scrollLeft= a[1];
}
}
}//by http://www.jb200.com

//在页面后台调用时的代码
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
call SaveDivScrollPosition("div1,div2,div3",me)
call RestoreDivScrollPosition("div1,div2,div3",me)
End Sub