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

作者 : 开心源码 本文共1491个字,预计阅读时间需要4分钟 发布时间: 2022-05-12 共251人阅读

开发的时候,我们有时不满意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('任务已经完成!!')});

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 用CSS和JS写一个简单的进度条

发表回复