js倒计时

效果如图:

javascript:

// 页面加载完成后运行
window.onload = function () {
   
    // 定时器,每隔一段时间刷新剩余时间
    var _run = setInterval(timeAuto,200);
   
    // 点击按钮重新计算剩余时间
    document.getElementById("change").onclick = function () {
            clearInterval(_run);
            _run = setInterval(timeAuto,1000);
        }
   
    function timeAuto() {
   
        // 获取结束时间,Data()内使用数字,需转换
        var endTimeTxt = end1 = end2 = new Array();
        endTimeTxt = document.getElementById("end").value.split(" ");
        end1 = endTimeTxt[0].split("-");
        end2 = endTimeTxt[1].split(":");
        var endTime = new Date(parseInt(end1[0]),parseInt(end1[1])-1,parseInt(end1[2]),parseInt(end2[0]),parseInt(end2[1]),parseInt(end2[2]));
   
        // 获取当前时间
        var nowTime = new Date();
   
        // 得到当前时间到结束时间之间时长,单位秒
        var now2endSecond = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
   
        var _d = parseInt((now2endSecond / 3600) / 24);  //天
        var _h = parseInt((now2endSecond / 3600) % 24);  //小时
        var _m = parseInt((now2endSecond / 60) % 60);  //分
        var _s = parseInt(now2endSecond % 60);  //秒
   
        // 如果倒计时完毕,则停止
        if (now2endSecond < 0) {
            clearInterval(_run);
            return
        }
   
        // 页面输出
        document.getElementById("time").innerHTML = "还有" + _d + "天" + _h + "小时" + _m + "分" + _s + "秒";
        document.getElementById("start").innerHTML = nowTime.getFullYear() + "-" + (nowTime.getMonth() + 1) + "-" + nowTime.getDate() + " " + nowTime.getHours() + ":" + nowTime.getMinutes() + ":" + nowTime.getSeconds();
   
    }
}

css:

* { padding: 0; margin: 0; }
   
body { font: 14px/20px Arial,"微软雅黑"; color: #333333; }
   
#content {
    width: 500px;
    height: 150px;
    border: 1px #e5e5e5 solid;
    background: #fcfcfc;
    position: absolute;
    top: 30%;
    left: 50%;
    margin-left: -250px;
    padding-top: 20px;
}
   
#content p { text-align: center; line-height: 40px; }
   
#content p span {
    display: inline-block;
    color: #808080;
    padding-right: 20px;
}
   
#time {
    text-align: center;
    color: #00bdf4;
    line-height: 50px;
    font-size: 20px;
}
   
#end {
    color: #808080;
    padding: 3px 0 3px 5px;
    font: 14px/20px Arial,"微软雅黑";
}
   
#change {
    border: 0;
    width: 70px;
    height: 25px;
    background: #00bdf4;
    color: #fff;
    cursor: pointer;
    font: 14px/25px Arial,"微软雅黑";
}

 

html:

<div id="content">
    <div id="time"></div>
    <p>
        当前时间:<span id="start"></span>结束时间:<input id="end" type="text" value="2020-2-20 10:23:00">
    </p>
    <p>
        <input id="change" type="button" value="刷新">
    </p>
</div>

posted @ 2014-12-03 11:44  K13  阅读(171)  评论(0编辑  收藏  举报