实例名称
通过JS记录滚动条位置
实例描述
当页面刷新时窗体中所有的内容会被重新初始化,但一些读书网站为了还原用户刷新前查看的内容,必须记录窗体滚动条的位置。本例介绍如何记录滚动条的位置。
实例代码
HTMLHEADTITLE 记录滚动条位置 -学无忧 language="javascript"u00a0function SetCookiesName, sValueu00a0u00a0u00a0date = new Date;u00a0u00a0s = ;u00a0u00a0+1;u00a0u00a0u00a0//设置cookie的有效期u00a0u00a0 = sName + "=" + escapesValue + "; expires=" + ;//创建cookieu00a0u00a0function GetCookiesNameu00a0u00a0u00a0var aCookie = "; "; //将cookie中的数据切割成数组,方便遍历u00a0u00a0for var i=0; i ; i++u00a0u00a0u00a0u00a0u00a0 //遍历cookie中的数据u00a0u00a0u00a0u00a0var aCrumb = "=";u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 //将键和值分开u00a0u00a0if sName == aCrumb0 u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 //判断是否是指定的键u00a0u00a0u00a0return unescapeaCrumb1;u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 //返回键对应的值u00a0u00a0u00a0u00a0return null;u00a0u00a0function winLoadu00a0u00a0u00a0 = GetCookie"scrollLeft";//获取水平滚动条位置u00a0u00a0 = GetCookie"scrollTop";u00a0 //获取垂直滚动条位置u00a0u00a0function winUnloadu00a0u00a0u00a0SetCookie"scrollLeft", u00a0 //保存水平滚动条位置u00a0u00a0SetCookie"scrollTop", u00a0u00a0u00a0 //保存垂直滚动条位置u00a0u00a0 = winLoad;u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 //加载页面时自动执行获取cookie保存值的方法u00a0 = winUnload;u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0u00a0 //关闭页面时自动执行保存cookie的方法/script/HEADBODY测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p测试行,主要为了出线滚动条p/p/BODY/HTML
运行效果
难点剖析
本例的重点是如何保存滚动条的位置。页面中的滚动条分为水平滚动条和垂直滚动条。水平滚动条的位置使用“document.body.scrollLeft”获取,垂直滚动条的位置使用“document.body.scrollTop”获取。保存滚动条位置使用的是Cookie,关于Cookie的操作可参考代码中的“SetCookie”和“GetCookie”方法。
源码下载