<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>progressBar</title>
<style>
#box {
margin: 0 auto;
margin-top: 200px;
width: 700px;
height: 100px;
background: #efefef;
border: 1px solid #C0C4CC;
display: flex;
justify-content: space-around;
align-items: center;
}
#progress {
position: relative;
width: 550px;
height: 30px;
border-radius: 6px;
background: #C0C4CC;
}
#fillContent {
position: absolute;
top: 0px;
left: 0px;
width: 0px;
height: 30px;
background: #409EFF;
border-radius: 6px;
}
button {
height: 30px;
width: 60px;
border-radius: 6px;
outline: none;
box-shadow: none;
border: none;
background: #409EFF;
padding: 0;
color: #fff;
}
button:hover {
cursor: pointer;
background: #5dadfd;
}
button:active {
cursor: pointer;
background: #0e84fa;
}
button:disabled {
cursor: not-allowed;
}
p {
width: 45px;
margin: 0;
text-align: right;
}
</style>
</head>
<body>
<div id="box">
<button onclick="start()">开始</button>
<div id="progress">
<div id="fillContent"></div>
</div>
<p id="percent">0%</p>
</div>
<script type="text/javascript">
// 获取所有需要的元素
let progress = document.querySelector("#progress");
let fillContent = document.querySelector("#fillContent");
let percent = document.querySelector("#percent");
let btn = document.querySelector("button");
// 获取整个进度条的宽度
let w = progress.clientWidth;
// 定义开始事件
function start() {
// 每次点击开始按钮初始化进度条状态
fillContent.style.width = 0 + 'px';
// 点击之后按钮设置为不可点击
btn.disabled = "disabled";
// 开启一个定时器
let timer = setInterval(function () {
// 进度条宽度每次增加1px
fillContent.style.width = fillContent.offsetWidth + 1 + "px";
// 计算进度条百分比数值
percent.innerHTML = parseInt((fillContent.offsetWidth / w) * 100) + "%";
// 当进度达到100%时,关闭定时器,按钮设置为可点击,进度条停止
if (fillContent.offsetWidth === w) {
clearInterval(timer);
btn.disabled = "";
}
}, 10);
}
</script>
</body>
</html>
原生js写一个简易版进度条,带百分比数值显示
最新推荐文章于 2024-05-02 09:34:08 发布