JavaScript学习笔记(一)——定时器

一、定时器

1.标准格式:window.setInterval('执行的代码串',间隔时间);

2.常见形式:

* setInterval('直接是操作',间隔时间)

* setInterval(function,间隔时间);//外调式

* setInterval('func(){}',间隔时间);//内嵌式

3.开启和关闭定时器的示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="start">开始定时器</button>
<button id="end">关闭定时器</button>


<script>
    window.onload=function(){
        var height=150;
        var timer=null;
        $('start').onclick=function () {
           timer=setInterval(
                function () {
                    height+=1;
                    console.log('身高是'+height+'cm');
                }
                ,1000
            );
        }
        $('end').onclick=function () {
            window.clearInterval(timer);


        }
        //!!!此处重点,十分常用的一种获取元素的函数
        function $(id) {
            return typeof id==='string'?document.getElementById(id):null;
        }
    }
</script>
</body>
</html>

二、时钟案例

<script>
    window.onload=function () {
        var hour=document.getElementById("hour");
        var min=document.getElementById("min");
        var sec=document.getElementById("sec");
        setInterval(function () {
            //获取当前时间戳
            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() % 12 + m / 60;

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

            // 2.3 旋转
            hour.style.transform = 'rotate('+ h * 30 +'deg)';
            min.style.transform = 'rotate('+ m * 6 +'deg)';
            sec.style.transform = 'rotate('+ s * 6 +'deg)';
        },10)
    }
</script>

     1.transform属性用于旋转div标签

      2. 为了使指针不是直直的指向数字,变量除了get到的确切值还要加一个偏角

      3.background属性中  的center;可以使元素居中div的中心部分

 

 

猜你喜欢

转载自blog.csdn.net/qq_40070622/article/details/81700087