js中的setInterval
跟几个例子吧
计时器的例子:
/** * Created by Administrator on 2016/8/5. */ (function () { function show() { var time = new Date(); document.body.innerHTML="当前时间为"+format(time.getHours()) +":"+format(time.getMinutes())+":"+format(time.getSeconds()); } function format(num) { if(num>=10){ return num; }else { return "0"+num; } } setInterval(function () { show(); },1000); show(); })();
进度条的例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .con{ width: 100%; height: 20px; background-color: cadetblue; } .bar{ height: 20px; background-color: coral; position: absolute; } .hu{ width: 100%; text-align: center; line-height: 20px; position: absolute; } </style> </head> <body> <div class="con"> <div class="bar"></div> <div class="hu">0%</div> </div> <script src="main01.js"></script> </body> </html>
/** * Created by Administrator on 2016/8/5. */ (function () { var width=1; var div=document.querySelector(".bar"); var divhu=document.querySelector(".hu"); function syBar() { var va=width+"%"; divhu.innerHTML=va; div.style.width=va; } var time=setInterval(function () { width++; syBar(); if(width>=100){ clearInterval(time); } },100); syBar(); })();
关于进度条说一点,注意加上单位(%或px),如
var va=width+"%";
divhu.innerHTML=va;
div.style.width=va;
这三行。
myGitgub https://github.com/mfx55
希望我的博客能帮到你