js简易电子时钟

  • Post author:
  • Post category:其他


setInterval计时器做一个简易电子时钟

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>电子时钟</title>
    <style>
        body {
            background: tomato;
        }
        section {
            height: 100px;
            width: 1000px;
            margin: auto;
            margin-top: 300px;
        }

        div {
            width: 100px;
            height: 100px;
            float: left;
            text-align: center;
            line-height: 100px;
            font-size: 40px;
            color: #ccc;
            font-weight: bold;
            background:orange;
        }
        span {
            float: left;
            font-size: 40px;
            padding: 50px;
            margin-top: -20px;
        }
    </style>
</head>

<body>
    <section>
        <div id="hours1"></div>
        <div id="hours2"></div><span>:</span>
        <div id="minutes1"></div>
        <div id="minutes2"></div><span>:</span>
        <div id="seconds1"></div>
        <div id="seconds2"></div>
    </section>
    <script type="text/javascript">
        window.onload = function () {
            var hours1, hours2, minutes1, minutes2, seconds1, seconds2;
            function init() {
                //获取所有DIV
                hours1 = document.getElementById("hours1");
                hours2 = document.getElementById("hours2");
                minutes1 = document.getElementById("minutes1");
                minutes2 = document.getElementById("minutes2");
                seconds1 = document.getElementById("seconds1");
                seconds2 = document.getElementById("seconds2");
                //开启时间间隔运行
                setInterval(date, 1000);
            }
            init();
            var hours, minutes, seconds;
            function date() {
                //获取当前时间,并且把当前时间转为字符,如果这个数字小于10,给前面加0;
                var _date = new Date();
                var hours = getString(_date.getHours());
                var minutes = getString(_date.getMinutes());
                var seconds = getString(_date.getSeconds());
                console.log(hours, minutes, seconds);
                //将当前时分秒显示在DIV中
                hours1.innerHTML = hours[0];
                hours2.innerHTML = hours[1];
                minutes1.innerHTML = minutes[0];
                minutes2.innerHTML = minutes[1];
                seconds1.innerHTML = seconds[0];
                seconds2.innerHTML = seconds[1];
            }
            //给入数字,如果小于10就加前导0,返回字符
            function getString(num) {
                if (num < 10) {
                    num = "0" + num;
                }
                return num.toString();
            }
        }
    </script>
</body>
</html>



版权声明:本文为Endeavorseven原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。