定时器之简单运动

在写完代码后,要注意代码是否有重复,把重复的部分封装成一个函数/方法,不同的的部分作为参数传入,如果可以,最好精简下参数,看是否可以传一个参数完成效果(PS:其他必要参数可在函数内部声明并赋值!)

注意:在使用定时器时,最好在每次运动开始之前,先清除掉之前的定时器,重新开始,否则线程中定时器过多,影响效果体现!!!
简单的鼠标移入移出,left值变化的小效果

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        html,body{
            margin:0;
            padding:0;
        }
        .square{
            position:relative;
            top:0px;
            left:-200px;
            width:200px;
            height:200px;
            background:deepskyblue;
        }
        .share{
            position:absolute;
            top:130px;
            left:200px;
            width:20px;
            height:55px;
            padding-top:15px;
            background:red;
            color:#000;
        }
    </style>
</head>
<body>
    <div id="square" class="square">
        <span id="share" class="share">分享</span>
    </div>
    <script>
        window.onload=function(){
            //获取到运动元素
            var sq=document.getElementById("square");
            //鼠标移入
            sq.onmouseover=function(){
                Move(0);
            }
            //鼠标移出
            sq.onmouseout=function () {
                Move(-200);
            }
        }
        var timer=null;
        function Move(oTarget){
            //每次运动前先清掉以前的定时器,重新开始
            clearInterval(timer);
            var sq=document.getElementById("square");
            var speed=0;
            timer=setInterval(function(){
                //判断speed正负
                if(sq.offsetLeft>oTarget){
                    speed=-10;
                }else{
                    speed=10;
                }
                //判断如果运动到了目标位置,就清楚定时器,停止运动
                if(sq.offsetLeft==oTarget){
                    clearInterval(timer);
                }else{
                    sq.style.left=sq.offsetLeft+speed+"px";
                }
            },30);
        }
 
    </script>
</body>
</html>


可以进群领取资料哦~WEB前端学习交流群21 598399936
posted @ 2017-12-11 14:06  噜噜修  阅读(210)  评论(0)    收藏  举报