时钟案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }

        #box{
            width: 600px;
            height: 600px;
            background: url("images/clock.jpg") no-repeat;
            margin: 20px auto;
            position: relative;
        }

        #hour, #min, #second{
            position: absolute;
            left: 50%;
            top: 0;
            width: 30px;
            height: 600px;
            margin-left: -15px;
        }

        #hour{
            background: url("images/hour.png") no-repeat;
        }

        #min{
            background: url("images/minute.png") no-repeat;
        }

        #second{
            background: url("images/second.png") no-repeat;
        }
    </style>
</head>
<body>
    <div id="box">
        <div id="hour"></div>
        <div id="min"></div>
        <div id="second"></div>
    </div>
<script>
    window.onload = function (ev) {
        // 1. 获取需要的标签
        var hour = document.getElementById('hour');
        var min = document.getElementById('min');
        var second = document.getElementById('second');

        // 2. 开启定时器
        setInterval(function () {
            // 2.1 获取当前的时间
            var date = new Date();

            // 2.2 转化时分秒
            var millS = date.getMilliseconds();
            var s = date.getSeconds() + millS / 1000;
            var m = date.getMinutes() + s / 60;
            var h = date.getHours() + m / 60;

            // console.log(s, m, h);

            // 2.3 旋转
            hour.style.transform = 'rotate(' + h * 30 + 'deg)';
            min.style.transform = 'rotate(' + m * 6 + 'deg)';
            second.style.transform = 'rotate(' + s * 6 + 'deg)';

        }, 10);
    }
</script>
</body>
</html>
 window.onload = function (ev) {
       // 1. 获取box
       var box = document.getElementById('box');
       var height = 0, intervalId;

       // 2. 监听鼠标进入 (先清除后设置)
        box.addEventListener('mouseover', function (ev1) {
            // 清除定时器
            clearInterval(intervalId);

             // 设置一个定时器
            intervalId = setInterval(function () {
                 height += 1;
                 console.log(height);
             }, 1000);
        });
    }

定时器先清除后设置,避免定时器的累加

posted @ 2019-07-16 22:08  疏影横斜水清浅  阅读(233)  评论(0编辑  收藏  举报