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>
相關文章
相關標籤/搜索