javascript - 一个进度条类的实现
阿神
阿神 2017-04-11 11:33:44
[JavaScript讨论组]

想实现一个进度条插件。

需求

push()方法将事件推送进事件队列。最后调用finished()进行读取。

progress().push(fn1).push(fn2).finished()

实现问题

  • push() 已经完成,并且finished() 可以推出执行队列,并依次执行。但是每次执行时,总是先完成进度条,然后在执行finished();

  • 程序最好是先执行完push内容,然后加载进度条。然后再进行下一个push内容。

 (function(){
    var progress = function(option){
        return progress.prototype.init(option);
    }
    
    progress.fn = progress.prototype = {
      init: function(option){
          // 初始化
        this.__totel = 0;   // 全部进程数
        this.__index = 0;   // 执行顺序
        this.__fnList = []; // 执行队列

        this.option = this.setOption({
          style: 'bootsrap',
          context: document
        }, option);


        this.creat(this.option.context);
        return this;
      },
      setOption: function(obj, option){
          var i;
        option = option || {};
        for (i in obj){
            if(option[i]){
                obj[i] = option[i] !== obj[i]? option[i] :obj[i];
            }
        }
        return obj;
      },
      creat: function(context){
        $(context).html('<p class="progress progress-striped active"> <p class="progress-bar" style="width: 2%"></p></p>')
        this.option.progress = $('.progress');
        this.option.bar = $('.progress>.progress-bar');
      },
      push: function(fn){
        this.__totel ++;
        this.__fnList.push(fn);
        return this;
      },
      finished: function(){
        for(; this.__index++ < this.__totel;){
          var fn = this.__fnList.shift();
          fn.call(this, this.__index);
        }
      },
      haved: function(i){
        console.log('__index:'+this.__index+',totol:'+this.__totel);
        var progress = this.option.progress,
            bar = this.option.bar;
        bar.css({'width': i/(this.__totel)*100+'%'});

        if(this.__index === 0){
          setTimeout(function(){
            progress.remove();
          }, 600)
        }

      }

使用:

    $('#test').click(function(){
        progress({context: '#content-progress'}).push(function(i){
            this.haved(i)
            setTimeout(function(){
                console.log('i'+i); 
            },1000)

        }).push(function(){
            var d = setTimeout(function(){
                console.log('4');
            },1000)
        }).finished()
    })

结果:

__index:1,totol:2
__index:2,totol:2
i1
2
阿神
阿神

闭关修行中......

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号