当div中绑定数据,给它一个属性overflow-y: scroll,添加长度大小,使其能够出现滚动条;每次刷新的时候滚动条总是会出现在最上方,这使我很头疼,经过查阅网上资料,返现两种方法可行。如下:

第一种方案

  将上一个页面的div的scrolltop距离长度记录在cookie中,然后通过js调整刷新页面时的长度记录,代码如下:

js代码:

 

 

 

 

 

html中代码如下:

 


            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

            

1

        

 

第二种方案

  1.通过div的onscroll事件记录滚动条的scrollTop值,设置到document.cookie
  2.页面加载时再读取document.cookie的值,设置给div的scrollTop

js代码实现:

 

        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]);
                
            }
        }
    

 

html:


              

            1

                        

            2

                        

            3

                        

            4

                        

            5

                        

            6

                        

            7

                        

            8

                        

            9

                        

            10

                        

            11

                        

            12

                        

            13

                        

            14

                        

            15

                        

            16