问答详情
源自:2-1 JS速度动画

本次课程的源码

没有全部的源码?跪求源码

提问者:人本多学点 2016-11-02 19:09

个回答

  • 苏明山下
    2016-11-03 11:07:59

    <!DOCTYPE html>

    <html>


    <head>

        <meta charset="UTF-8">

        <title>Document</title>

        <style type="text/css">

            * {

                margin: 0;

                padding: 0;

                font-size: 12px;

            }

            

            div {

                width: 200px;

                height: 200px;

                background: green;

                position: relative;

                left: -200px;

            }

            

            span {

                width: 30px;

                height: 30px;

                line-height: 30px;

                background: red;

                position: absolute;

                left: 200px;

                top: 85px;

                text-align: center;

                cursor: pointer;

            }

        </style>

    </head>


    <body>

        <div id="div">

            <span id="show">show</span>

        </div>


        <script>

            function $(id) {

                return typeof id === "string" ? document.getElementById(id) : id;

            }


            window.onload = function() {


                //定义变量

                var pto = $("div");

                var btn = $("show");

                var timer = null;

                var speed = 0;


                //鼠标移动绑定事件(一个无名函数)

                btn.onmouseenter = function() {

                    //调用自定义函数,传入参数0为pto.offsetLeft需要达到的距离

                    showPto(0);

                }

                //同理

                btn.onmouseleave = function() {

                    //同理

                    showPto(-200);

                }


                //自定义函数,one为自定义参数

                function showPto(one) {

                    //当前只需要一个定时器,所以需要在每次开始前清除定时器

                    clearInterval(timer);

                    //定义一个名为timer的定时器

                    timer = setInterval(function() {

                        if (one > pto.offsetLeft) {

                            //当0>pto.offsetLet时,pto需要被显示,所以speed为正值

                            speed = 10;

                        } else {

                            //同理,需要被隐藏时,speed为负值

                            speed = -10;

                        }

                        if (pto.offsetLeft == one) {

                            //当pto的值达到0或者-200时候就达到需求了,需要停止定时器,

                            clearInterval(timer);

                        } else {

                            //没有到0或者-200时候,就需要通过speed来自增或自减

                            pto.style.left = pto.offsetLeft + speed + 'px';

                        }


                    }, 30);

                }

            }

        </script>

    </body>


    </html>

    更多课程代码,可以去我的博客:http://www.cnblogs.com/WhiteM/