记住滚动条位置的 js

本文介绍了一种使用JavaScript记录和恢复网页滚动条位置的方法,通过在页面加载和卸载时保存滚动状态,实现用户体验的优化。文章提供了具体的代码实现,包括利用userData和cookie两种方式来存储滚动信息。

//记录滚动条位置
$(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;
}
})

转载于:https://www.cnblogs.com/Vijolee/p/4363268.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值