用CSS和JS写一个简单的进度条

开发的时候,我们有时不满意Bootstrap之类内置的进度条,可以自己写一个轻量级的ProgressBar工具类,来定制自己的需求。该ProgressBar类且在完成之后会调用传入的回调函数

效果图如下

ssss.gif

测试页面

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Async JS</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/test.css') }}">
</head>
<body>
<div class="main">
    <h2>进度 </h2>
   <div class="progressBar" data-label="loading"></div>
</div>
</body>
<script src="{{ url_for('static', filename='js/business/test.js') }}"></script>
</html>

CSS样式表

body{
  padding:auto;
  margin:auto;
}

div.main{
  display: inline-flex;
  border:1px solid #ccc;
  padding:10px;

}


.progressBar{
  box-sizing: border-box;
  position: relative;
  width:200px;
  height: 2.5em;
  background-color: rgba(218, 218, 218, 0.38);
  border-radius: 1em;
  color:white;
  margin:auto;
}

.progressBar::before{
  box-sizing:border-box;
  content:attr(data-label);
  display: flex;
  align-items: center;
  position: absolute;
  left: .5em;
  top:.5em;
  bottom: .5em;
  width: calc(var(--width,0)*1%);
  min-width: .1em;
  max-width: calc(100% - 1em);
  background-color:#080;
  border-radius: .6em;
  padding:.5em;
}

ProgressBar工具类

该工具类使用setInterval函数模拟了进度条的加载进度,实际开发中读者可以自己放入自己业务代码,唯一不改动的核心的函数就是getComputeStyle和style.setProperty,具体用法请参考MDN开发文档

class ProgressBar{
    constructor(callback){
        this.pb=document.querySelector('div.progressBar');
        this.refId=setInterval(()=>{
            const comp=window.getComputedStyle(this.pb);
            const width=parseFloat(comp.getPropertyValue('--width')) ||0;
            this.pb.style.setProperty('--width',width+.1);

            if(width>=100){
                clearInterval(this.refId);
                if(typeof(callback)=='function'){
                    callback();
                }
            }
        },5)
    }
}

pb=new ProgressBar(()=>{alert('任务已经完成!!')});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容