为了账号安全,请及时绑定邮箱和手机立即绑定

怎么用JS写一个倒计时

怎么用JS写一个倒计时

慕粉1217083117 2017-02-05 10:11:21
查看完整描述

3 回答

?
KevenHuang

TA贡献280条经验 获得超233个赞

一小时倒计时,代码如下:

//img1.sycdn.imooc.com//5897cfeb00014c4e03380231.jpg

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>js实现倒计时思路</title>
    <style type="text/css">
        *{
            margin:0;
            padding:0;
            font-size:50px;
        }
        #wrap{
            width:300px;
            height:200px;
            border:1px solid #abcdef;
            position:absolute;
            left:50%;
            top:50%;
            transform:translate(-50%,-50%);
            text-align:center;
            line-height:200px;
        }
    </style>
    <script type="text/javascript">
        window.onload = function(){
            var hour = document.getElementById('hour');
            var minute = document.getElementById('minute');
            var second = document.getElementById('second');
            var hourNum = 0;
            var minuteNum = 59;
            var secondNum = 60;
            var timer = window.setInterval(function(){
                if(secondNum!=0){
                    secondNum--;
                    if(secondNum<10){
                        secondNum = '0'+secondNum;
                    }
                }else{
                    secondNum = 59;
                    //秒数为零时,时间走了一分钟,分钟数要减一
                    minuteNum--;
                    if(minuteNum<10&&minuteNum>0){
                        minuteNum = '0'+minuteNum;
                    }
                }
                if(minuteNum == 0){
                    //分钟数为零时,时间走了一小时,停止定时器
                    secondNum = '00';
                    minuteNum = '00';
                    window.clearInterval(timer);
                }
                hour.innerHTML = hourNum;
                minute.innerHTML = minuteNum;
                second.innerHTML = secondNum;
            },1000);
        }
    </script>
</head>
<body>
    <div id="wrap">
        <span id="hour">1</span>:<span id="minute">00</span>:<span id="second">00</span>
    </div>
</body>
</html>


查看完整回答
1 反对 回复 2017-02-05
  • 3 回答
  • 2 关注
  • 1907 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信