首页 > 代码库 > 一个简单的js实现倒计时函数

一个简单的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-21 00:00:00;
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;
    //&&只能用一次,所以分开两个if判断&&
    }else if(remainDays == 0 && remainHours == 0){
        if(remainMinutes == 0 && remainSeconds == 0){
            div1.innerHTML = 活动已经结束;
            clearInterval(k);//清除定时器
            return;
        }
    }
    div1.innerHTML = ‘‘;
    div1.innerHTML = endtime;
}
var k =setInterval("daoji(stringTime)",1000);
</script>

 

一个简单的js实现倒计时函数