您的位置:首页 > Web前端 > JavaScript

用JS实现页面滚动位置保持的方法

2006-05-29 12:11 981 查看
c#
step 1
replace the tag of <body> with the follewing codes:

<%
if (Request["__SCROLLPOS"] != null &&
Request["__SCROLLPOS"] != String.Empty) {
int pos = Convert.ToInt32 (Request["__SCROLLPOS"]);
Response.Write ("<body id=\"theBody\" " +
"onscroll=\"javascript:document.forms[0].__SCROLLPOS.value = " +
"theBody.scrollTop;\" " +
"onload=\"javascript:theBody.scrollTop=" + pos + ";\">");
}
else {
Response.Write ("<body id=\"theBody\" " +
"onscroll=\"javascript:document.forms[0].__SCROLLPOS.value =" +
"theBody.scrollTop;\">");
}
%>

step 2
add the follewing codes between <form> and </form>

<input type="hidden" name="__SCROLLPOS" value="" />

vb
 

step 1
replace the tag of <body> with the follewing codes:

<%
If Not Request("__SCROLLPOS") Is Nothing then
if Request("__SCROLLPOS") <> String.Empty Then
Dim pos As Integer = CType(Request("__SCROLLPOS"), Integer)
Response.Write("<body id=""theBody"" onscroll=""javascript:document.forms[0].__SCROLLPOS.value = theBody.scrollTop;"" onload=""javascript:theBody.scrollTop=" + pos.tostring + ";"">")
end if
else
response.Write("<body id=""theBody"" onscroll=""javascript:document.forms[0].__SCROLLPOS.value =theBody.scrollTop;"">")

end if
%>

step 2
add the follewing codes between <form> and </form>

<input type="hidden" name="__SCROLLPOS" value="" />

js版的:)

<!--
Created by 宝玉 , 2004-2-21 http://www.webuc.net
Description: 记录页面上次的滚动条位置
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> 记录滚动条位置 </TITLE>

<script language="javascript">
<!--
// 获取当前文件名
function getFileName()
{
var url = this.location.href
var pos = url.lastIndexOf("/");
if(pos == -1)
pos = url.lastIndexOf("\\")
var filename = url.substr(pos +1)
return filename;
}

function fnLoad()
{
with(window.document.body)
{
addBehavior ("#default#userData"); // 使得body元素可以支持userdate
load("scrollState" + getFileName()); // 获取以前保存在userdate中的状态
scrollLeft = getAttribute("scrollLeft"); // 滚动条左位置
scrollTop = getAttribute("scrollTop");
}
}

function fnUnload()
{
with(window.document.body)
{
setAttribute("scrollLeft",scrollLeft);
setAttribute("scrollTop",scrollTop);
save("scrollState" + getFileName());
// 防止受其他文件的userdate数据影响,所以将文件名加上了
// userdate里的数据是不能跨目录访问的
}
}
window.onload = fnLoad;
window.onunload = fnUnload;

// -->
</script>
</HEAD>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: