记住滚动条位置的 js

时间:2021-09-26 10:31:11

//记录滚动条位置
$(function () {
// 获取当前文件名
function getFileName() {
var url = this.location.href
var pos = url.lastIndexOf("/");
if (pos == -1)
pos = url.lastIndexOf("\\")
var filename = url.substr(pos + 1)
//alert(filename);
return filename;

}
function fnLoad() {
with (window.document.documentElement) {
addBehavior("#default#userData");
//使得body元素可以支持userdate
//load("scrollState" + getFileName()); // 获取以前保存在userdate中的状态 getFileName()记录每一页的每一个记录
load("scrollState");
scrollLeft = getAttribute("scrollLeft");
//滚动条左位置
scrollTop = getAttribute("scrollTop");
alert(scrollLeft + ":" + scrollTop);
}
}
function fnUnload() {
with (window.document.documentElement) {
setAttribute("scrollLeft", document.documentElement.scrollLeft);
setAttribute("scrollTop", document.documentElement.scrollTop);
//save("scrollState" + getFileName()); //记录每一页的每一个记录
save("scrollState");
// 防止受其他文件的userdate数据影响,所以将文件名加上了
// userdate里的数据是不能跨目录访问的
}
}
window.onload = fnLoad;
window.onunload = fnUnload;
//多个onload事件同时触发
window.onload = function () {
fnLoad();
}
//在关闭和刷新浏览器触发
window.onunload = fnUnload;
function fnLoad() {
var arr;
if (arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/))
document.documentElement.scrollTop = parseInt(arr[1]);
if (arr == null || arr == "null") { }
else { document.body.scrollTop = parseInt(arr[1]); }
}
//页面刷新前保存滚动条位置信息到cookie
function fnUnload() {
var scrollPos;
if (typeof window.pageYOffset != 'undefined') {
scrollPos = window.pageYOffset;
}
else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
scrollPos = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined') {
scrollPos = document.body.scrollTop;
}
document.cookie = "scrollTop=" + scrollPos;
}
})