js用定时器实现进度条

 

<!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>
</head>
<style>
* {
margin: 0;
padding: 0;
}

h1 {
margin-bottom: 30px;
margin-left: 100px;
}

#box {
width: 0;
height: 40px;
background: #58bc58;
}
</style>

<body>
<h1>进度条</h1>
<div id="box">

</div>
<span id="s1"></span>
<script>
var iwidth = 0;//设置初始长度为0
var box = document.getElementById("box");//获取元素
var s1 = document.getElementById("s1");
var winwidth = document.documentElement.clientWidth;
console.log(winwidth);

function jindu() {//封装函数
iwidth += 25;//每次增加5像素
if (iwidth >= winwidth) {//如果达到最大值就不在增加
iwidth = winwidth;
clearInterval(timer);//定时器停止
}
var s1num = (iwidth / winwidth * 100).toFixed(2) + "%";//计算百分比
s1.innerHTML = s1num;//写入
console.log(s1num);
box.style.width = iwidth + "px";//给元素设置宽度样式
}

var timer = setInterval(jindu, 100);//定时器每隔100毫秒执行一次



</script>
</body>

</html>
posted @ 2019-04-06 14:49  sun丶凹凸曼  阅读(1124)  评论(0编辑  收藏  举报