用Javascript 实现倒计时

时间:2023-01-11 22:01:13
用Javascript 实现倒计时
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .time1{ width: 500px; height: 300px; background-color: #cccccc; color: red; border: 1px solid green; margin: 100px auto; } </style> </head> <body> <div class="time1"></div> <script> var div=document.getElementsByClassName("time1")[0]; //定义一个计时器 setInterval(fn,1); //封装成功方法,每隔固定时间调用一次 function fn() { //1.获取时间差,将来的时间剪去现在的时间 var futureTime=new Date("2018/09/08 01:00:00"); var nowTime=new Date(); //时间差(毫秒值)=未来时间-当前时间 var sumMS=futureTime.getTime()-nowTime.getTime(); //2.把时间差转化成:天时分秒毫秒 var day=parseInt(sumMS/1000/60/60/24); var hour=parseInt(sumMS/1000/60/60%24); var minute=parseInt(sumMS/1000/60%60); var second=parseInt(sumMS/1000%60); var ms=parseInt(sumMS%1000); day=day<10?"0"+day:day; minute=minute<10?"0"+minute:minute; hour=hour<10?"0"+hour:hour; second=second<10?"0"+second:second; if(ms<10){ ms="00"+ms; }else if (ms<100){ ms="0"+ms; } //3.把天时分秒毫秒整合成字符串后赋值给div的innerHTML div.innerHTML="距苹果发布会还有:"+day+"天"+hour+"小时"+minute+"分"+second+"秒"+ms+"毫秒" } </script> </body> </html>