时间:2020-11-30 13:00:44 | 栏目:JavaScript代码 | 点击:次
实现倒计时效果需要掌握js中的两个知识点:
1、setTimeout函数 每隔1秒钟更新秒钟时间
2、Date对象 计算时间差
下面贴出 元旦倒计时代码
<!DOCTYPE html> <html> <head> <title>example.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script> //定义计时器,每隔1秒钟调用timer函数 var timerCount= window.setTimeout("timer()",1000); function timer(){ var date=new Date("2017","1","1","0","0","0"); var deadlineTime=date.getTime(); var nowDate=new Date(); var nowTime=nowDate.getTime(); var distTime=deadlineTime-nowTime; //判断是否到达时间期限 if(distTime>0){ var d=Math.floor(distTime/1000/3600/24); var h=Math.floor(distTime/1000/3600%24); var m=Math.floor(distTime/1000/60%60); var s=Math.floor(distTime/1000%60); var str="距离2017年元旦还有"+d+"天"+h+"时"+m+"分"+s+"秒"; document.getElementById("timeout").innerHTML=str; timerCount= window.setTimeout("timer()",1000); } else{ //到达时间期限的时候清楚计时器; window.clearTimeout(timerCount); alert("时间已到"); } } </script> </head> <body> <p id="timeout"> </p> </html>