• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ranying
博客园    首页    新随笔    联系   管理    订阅  订阅
如何实现进度条效果呢 ?
实现页面进度条

如何实现进度条效果呢 ?

  • 效果:点击页面的某个按钮,弹出一个进度条,然后实时显示进度,直到任务完成。
  • 思路:页面里面有个隐藏的进度条,点击按钮后弹出。ajax循环请求数据,直到全部完成
  • 难点:ajax的同步请求问题

  1、首先引入页面样式:

   
       .myProgressDiv{
            width:450px;
            border:1px solid #6C9C2C;
            border-radius: 8px;
            height:25px;
        }

        #bar{
            background:#20B2AA;
            float:left;
            height:100%;
            text-align:center;
            line-height:150%;
            border-radius: 8px;
        }
        #maskDiv{
            position: fixed;
            /*top: 0;*/
            top:-150px;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 20;
        }
        #progressBox{
            position: relative;
        }
        #total{
            font-size: 1.2em;
            position: absolute;
            left: 48%;
            top: 10%;
        }    

  2、页面 进度条 HTML 元素

<div id="maskDiv" style="display: none">
    <div id="progressBox">
        <div class="myProgressDiv">
            <div id="bar" style="width:0%;"></div>
        </div>
        <span id="total"></span>
    </div>
</div>

  3、JS 实现

 

       定义全局的变量 i = 0 , n = 12; 一共请求多少次(服务器返回)
  点击按钮后


  $("#maskDiv").show();
  syncPage();

var bar = document.getElementById("bar");
var total = document.getElementById("total");

function syncPage() {
    if (n < i ) {
        bar.style.width = "100%";
        total.innerHTML = bar.style.width;
        return;
    }
    $.ajax({
        url: ctx + '/../../sync_page_data', //服务器端请求地址
        method:'post',
        dataType: 'json',
        data:{"offset" : i * 20,"count": 20},
        async: true,
        success: function (data){
            i++;
            if(data && data.flag){
                let progress = Math.ceil(i/n * 100);
                if(progress>99){
                    progress = 99;
                }
                bar.style.width= progress  + "%";
                total.innerHTML = bar.style.width;
                console.info(bar.style.width);
                timeout= window.setTimeout("syncPage()",100);

            }else{
                $("#maskDiv").hide();
                bar.style.width = 0;
                layer.alert('操作失败:'+data.message, {icon: 2});
            }
        },
        error: function (data, status, e){
            layer.msg('网络错误,同步失败');
        }
    });
}

  

  重点: timeout= window.setTimeout("syncPage()",100); 递归调用

  这样一个完整的进度条就实现了。

 

posted on 2018-08-10 11:04  ranying  阅读(1415)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3