一個簡單的js實現倒計時函數

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>js實現倒計時</title>
    <meta name="keywords" content="關鍵字列表" />
    <meta name="description" content="網頁描述" />
    <link rel="stylesheet" type="text/css" href="" />
    <style type="text/css"></style>
    <script type="text/javascript">
    </script>
</head>
<body>
<div></div>
</body>
</html>
<script>
//函數的參數爲活動的結束日期
var stringTime = '2016-12-22 21:23:10';
function daoji(stringTime){
    //獲取即時時間的對象
    var now = new Date();
    //獲取結束時間的對象
    var end = new Date(stringTime);
    //獲取即時的時間戳
    var nowTimeStamp = now.getTime();
    //獲取活動結束的時間戳
    var endTimeStamp = end.getTime();
    //活動剩餘秒數,js的時間戳是毫秒級別的
    var remainSecond= (endTimeStamp - nowTimeStamp) / 1000;
    //剩餘的秒數等於days+hours+minutes+seconds
    var oneDay = 24*60*60;
    var oneHour = 60*60;
    var oneMinute = 60;
    //剩餘的天數
    var remainDays      = parseInt((remainSecond / oneDay));
    //減掉整數的天數,並對剩下的進行小時取整就是剩下的小時
    var remainHours   = parseInt(((remainSecond - (remainDays*oneDay)) / oneHour));
    var Hours = parseInt((remainSecond / oneHour));
    //減掉整數的小時,並對剩下的進行分鐘取整就是剩下的分鐘數
    var remainMinutes = parseInt((remainSecond - (Hours*oneHour)) / oneMinute);
    //減掉整數的分鐘就是剩下的秒數
    var Minutes = parseInt(remainSecond / oneMinute);
    var remainSeconds = parseInt(remainSecond - (Minutes * oneMinute));
    //倒計時開始
    var endtime = remainDays + ''+ remainHours + '小時'+ remainMinutes +'分鐘'+ remainSeconds +'';
    var div1 = document.getElementsByTagName('div')[0];
    if(remainDays < 0 || remainHours < 0 || remainMinutes < 0 || remainSeconds < 0){
        div1.innerHTML = '活動已經結束';
        clearInterval(k);
        return;
    //判斷活動是否到期
    }else if(remainDays == 0 && remainHours == 0 && remainMinutes == 0 && remainSeconds == 0){
            div1.innerHTML = '活動已經結束';
            clearInterval(k);//清除定時器
            return;
    }
    div1.innerHTML = '';
    div1.innerHTML = endtime;
}
var k =setInterval("daoji(stringTime)",1000);
</script>
相關文章
相關標籤/搜索