實現倒計時效果需要掌握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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。