前端开发定时器之简单运动

前端开发技术认识
wed前端开发技术 ppt
web前端开发的技术架构

在写完代码后,要注意代码是否有重复,把重复的部分封装成一个函数/方法,不同的的部分作为参数传入,如果可以,最好精简下参数,看是否可以传一个参数完成效果(PS:其他必要参数可在函数内部声明并赋值!)
注意:在使用定时器时,最好在每次运动开始之前,先清除掉之前的定时器,重新开始,否则线程中定时器过多,影响效果体现!!!
简单的鼠标移入移出,left值变化的小效果
html 代码

<!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前端开发技术介绍
前端开发技术jsp
web前端开发技术英文
赞(0)
前端开发者 » 前端开发定时器之简单运动
64K

评论 抢沙发

评论前必须登录!