美文网首页
JavaScript基础 运动框架 案例

JavaScript基础 运动框架 案例

作者: 0说 | 来源:发表于2018-02-11 14:11 被阅读0次
Animation.gif
<style type="text/css">
    /*清除样式*/
    *{margin: 0;padding: 0;}
    ul li{list-style-type: none;}
    a{text-decoration: none; color: inherit;}
    /*---------------------------------------------------*/
    img{
        display: block;
        position: relative;
        left: 500px;
        width: 258px;
        height: 194px;
        margin-top: 50px;

    }


</style>
</head>
<body>
    <img src="images/1.gif" width="258" height="194"/>
    <script src="js/move.js"></script>
    <script>
        !function () {
            var oImg = document.getElementsByTagName( 'img')[0],
                arr = [],
                onoff,
                timer,
                left = parseFloat( getStyle( oImg ).left );

            /*
                思路:
                    定一个数组,同一个数字存正负 [20,-20,19,-19,18,18.....0,-0],移入的时候 从数组0位取到最后一位,设置left的值

             */
            for ( var i=20 ; i>=0 ; i-- ){
                arr.push( i,-i );
            }
            oImg.onmouseenter = function () {
                if( onoff ){ return 6666 };
                onoff = true; //开启开关  还没执行到 下面 if( num === arr.length - 1 ) 的时候开关是开的  上面if(onoff)会执行,下面代码不会执行,也就是说还没执行到把开关关的代码;
                var num = 0;
                timer = setInterval( move.bind(oImg) , 1000/60 ); //改变this指向
                function move (  ) {
                    num ++;
                    this.style.left = arr[num]+left+'px';
                    if( num === arr.length - 1 ){
                        clearInterval( timer );//当num到 arr.length长度的时候清除定时器
                        onoff = false; //把定时器变为假的  只有代码执行到这里的时候 才会关了开关
                    }
                }
            }
        } ();

        function getStyle(obj){
            return obj.currentStyle || getComputedStyle( obj );
        }   
    </script>

相关文章

网友评论

      本文标题:JavaScript基础 运动框架 案例

      本文链接:https://www.haomeiwen.com/subject/twiktftx.html