js實現重新整理頁面後回到記錄時滾動條的位置
阿新 • • 發佈:2019-01-02
區域性重新整理後,要求滾動條在原下拉時的位置:
1、將頁面的div的scrolltop距離長度記錄在cookie中,然後通過js調整重新整理頁面時的長度記錄,程式碼如下
<div id="x" style="height: 200px; overflow: scroll" onscroll="SetH(this)">
</div>
<script>
var _h = 0;
function SetH(o) {
_h = o.scrollTop
SetCookie("a", _h)
}
function SetCookie(sName, sValue) {
document.cookie = sName + "=" + escape(sValue) + "; ";
}
window.onload = function () {
document.getElementById("x").scrollTop = GetCookie("a");//頁面載入時設定scrolltop高度
}
function GetCookie(sName) {
var aCookie = document.cookie.split("; ");
for (var i = 0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
return 0;
}
</script>
注意:
document.getElementById("x").scrollTop = GetCookie("a");
要在ajax返回成功後執行
$.ajax({url:"",
type:"Post",
data:Data,
success:function(data){
document.getElementById("ty0" ).scrollTop = GetCookie("a");//頁面載入時設定scrolltop高度
}
});
2、“
<div class="content" data-role="tab-content" data-id="course-a" runat="server" id="divContent" style="height: 365px; overflow-y: scroll" onscroll= "KeepScrollBar()">
</div>
<script type="text/javascript">
function KeepScrollBar() {
var scrollPos;
if (typeof window.pageYOffset != 'undefined') {
scrollPos = window.pageYOffset;
}
else if (typeof document.body != 'undefined') {
scrollPos = document.getElementById('divContent').scrollTop;
}
document.cookie = "scrollTop=" + scrollPos;
}
window.onload = function (){
if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) {
var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/);
document.getElementById('divContent').scrollTop = parseInt(arr[1]);
}
}
</script>