跌倒的马铃薯

 

自动恢复滚动状态

          在进行网页操作中经常会刷新,当然AJAX等除外。在刷新之前用户当前操作页面可能使用滚动条滚动过(Scroll),刷新之后页面滚动条又会回到起初的状态。这在有些时候是不能容忍的,比如对树的展开操作。如果用户每展开一层都需要重新拖动滚动条到上次位置,那他一定会疯掉的。于是就有了以下的解决方法。

        首先将ScrollMonitor绑定到传入控件的onscroll事件上,然后将控件放到一个Array里面。

function AutoReScroll()
{
    
this.Objs = new Array();
    
//public
    this.RegControl = function (oCtrl)
    
{
        
if (oCtrl != null && typeof(oCtrl.onscroll) != "undefined")
        
{
            oCtrl.onscroll 
= this.ScrollMonitor;
            
this.Objs.push(oCtrl);            
        }

        
else
        
{
            alert(
"Control can't be null or has not 'onscroll' event!");
        }

        
    }

       ScrollMonitor的实现,非常简单。将传入控件的scrollTop值保存到Cookie

//private
    this.ScrollMonitor = function ()
    
{     
        set_Cookie(document.location.pathname 
+ this.id,this.scrollTop,365);
    }

       
从Array中取出所有控件,并将保存在Cookie中的数据赋给控件。

this.RestoreScroll = function ()
    
{
        
for(var i = 0;i<this.Objs.length;i++)
        
{
            
if (typeof(this.Objs[i].scrollTop) != "undefined")
            
{
                
this.Objs[i].scrollTop = get_cookie(document.location.pathname + this.Objs[i].id);        
            }

        }

    }

假如对Body控制,由于在ScrollMonitor中的this不是body,所以单独写了一个函数处理body

 

this.AutoBodyScroll = function ()
    
{
        document.body.onscroll 
= function () {set_Cookie(document.location.pathname + "body",document.body.scrollTop,365);}
        document.body.scrollTop 
= function () {document.scrollTop = get_cookie(document.location.pathname + "body");        }
    }

还有两个操作Cookie的,不用我再说明了吧。在Demo中有实现。
      在IE5.5以上测试通过。
      下载Demo,使用方法如下:
        //声明一个对象

var LockTop = new AutoReScroll();
        //注册需要控制的元素,或者Body。一定要确保在运行注册时元素是可用的,所以最好将这段代码放到页尾。
LockTop.AutoBodyScroll();
LockTop.RegControl(document.getElementById(
"test1"));
LockTop.RegControl(document.getElementById(
"test3"));
LockTop.RegControl(document.getElementById(
"test2"));
LockTop.RegControl(document.getElementById(
"test4"));
        //恢复已注册的元素的滚动状态
LockTop.RestoreScroll();
        --完--

posted on 2006-05-25 13:10  Ivan  阅读(361)  评论(0)    收藏  举报

导航