学习JQuery写的第一个插件_屏幕滚动

Posted on 2008-09-18 17:24  BingLiang Sha  阅读(667)  评论(0编辑  收藏  举报
这个插件看起来是很简单的,但是setTimeout这个函数不小心就用不好。
jQuery.fn.scrollScreen=function(t){
    var time;
    //如果没有设置时间则默认设置为3秒
    if(t==undefined){
        time=3000;
    }
    else
        time=t;
    return this.each(function(){
        var $this=$(this);
        
        var timeout;
        var inProgress = false;
        
        var timer=function(){
            //上锁
            if(!inProgress){
                inProgress = true;
                //清空计数器堆栈,防止堆栈中存在多个计数器而出现“时间跳跃”
                timeout = false;
                var $first=$this.children(":first");
                $first.fadeOut(1000,function(){
                    $this.append($first);
                    var $last=$this.children(":last");
                    $last.show();
                    //处理完毕,解锁
                    inProgress=false;    
                });
                if(!timeout)
                    timeout=setTimeout(timer,time);    
            }
        };
        timeout=setTimeout(timer,time);
        $this.hover(function(){
            //停止计数,清空堆栈
            clearTimeout(timeout);
            timeout = false;
        },function(){
            if (!timeout) {
                timeout = setTimeout(timer, 500);
            }
        });
    });
}