法一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style>
#progress {
position: relative;
margin: auto;
top: 200px;
display: block;
width: 800px;
height: 40px;
border-style: dotted;
border-width: thin;
border-color: darkgreen;
}
#filldiv {
position: absolute;
top: 0px;
left: 0px;
width: 0px;
height: 40px;
background: -webkit-linear-gradient(right, #f00, #00f);
}
#percent {
position: absolute;
top: 0px;
left: 50%;
transform: translateX(-50%);
font-size: 32px;
}
</style>
</head>
<body>
<div id="progress">
<div id="filldiv"></div>
<span id="percent">0</span>
</div>
</body>
<script>
var oPercent = document.querySelector('#percent');
var oFilldiv = document.querySelector('#filldiv');
var oProgress = document.querySelector('#progress');
//用于计算百分比
var count = 0;
//定时器,每隔一定时间调用该方法,达到动态的效果
var timer = setInterval(function () {
count++;
//如果到达100,则说明百分比加载完,清除定时器
if (count >= 100) {
clearInterval(timer);
count = 100;
}
//填入百分比
oPercent.innerHTML = count + '%';
//使oFilldiv的宽度随着百分比的改变而改变
oFilldiv.style.width = oProgress.clientWidth * count / 100 + 'px';
}, 100);
</script>
</html>
法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#progress {
position: relative;
margin: auto;
top: 200px;
display: block;
width: 800px;
height: 40px;
border-style: dotted;
border-width: thin;
border-color: darkgreen;
}
#filldiv {
position: absolute;
top: 0px;
left: 0px;
width: 0px;
height: 40px;
background: -webkit-linear-gradient(right, #f00, #00f);
}
#percent {
position: absolute;
top: 0px;
left: 50%;
transform: translateX(-50%);
font-size: 32px;
}
</style>
</head>
<body>
<div id="progress">
<div id="filldiv"></div>
<span id="percent">0</span>
</div>
</body>
<script>
var pro = document.getElementById("progress")
var per = document.getElementById("percent");
var fill = document.getElementById("filldiv");
var timer;
//获取pro的width属性,并截取px之前的数字
var proWidth = getComputedStyle(pro)['width'].slice(0, -2);
var result;
//点击时启动进度条
pro.onclick = function () {
timer = setInterval(function () {
//获取fill的width属性,并截取px之前的数字
var fillWidth = getComputedStyle(fill)['width'].slice(0, -2); //string
//fillWidth的结果是字符串类型,要进行比较或计算必须先强制转化为数字类型
fillWidth = Number(fillWidth);
//如果填充的fill小于等于容器pro的宽度,则计算百分比,否则清除计时器
if (fillWidth <= proWidth) {
//百分比的计算,需先保留两位小数以后*100
result = Math.floor(((fillWidth / proWidth).toFixed(2)) * 100) + "%";
//填充的fill的宽度在不断变化
fillWidth = Number(fillWidth) + 10;
//并将其宽度赋值给对应属性
fill.style.width = fillWidth + "px";
//显示百分比
per.innerHTML = result;
} else {
clearInterval(timer)
}
}, 100);
}
</script>
</html>