js实现刷新页面后回到记录时滚动条的位置

第二种方案
1.通过div的onscroll事件记录滚动条的scrollTop值,设置到document.cookie
2.页面加载时再读取document.cookie的值,设置给div的scrollTop
<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>

  

<div class="content" data-role="tab-content" data-id="course-a" runat="server" id="divContent" style="height: 365px; overflow-y: scroll" onscroll= "KeepScrollBar()">
    <p>   1</p>   
    <p>   2</p>   
    <p>   3</p>   
    <p>   4</p>   
    <p>   5</p>   
    <p>   6</p>   
    <p>   7</p>   
    <p>   8</p>   
    <p>   9</p>   
    <p>   10</p>   
    <p>   11</p>   
    <p>   12</p>   
    <p>   13</p>   
    <p>   14</p>   
    <p>   15</p>   
    <p>   16</p> 
</div>

  

posted @ 2024-08-28 11:00  心无引擎,眼无流派  阅读(88)  评论(0编辑  收藏  举报