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

JavaScript基础 运动框架

作者: 0说 | 来源:发表于2018-02-07 17:11 被阅读0次
div从左到右运动! Animation.gif
div从左到右运动! Animation2.gif
 <style type="text/css">
        /*清除样式*/
        *{margin: 0;padding: 0;}
        ul li{list-style-type: none;}
        a{text-decoration: none; color: inherit;}
        /*---------------------------------------------------*/
        .wrap{
            position: relative;
            left: 1000px;
            width: 100px;
            height: 100px;
            margin-top: 50px;
            background: red;
        }
    </style>
</head>
<body>
    <div class="wrap"></div>
<script>
    var aWrap = document.getElementsByTagName( 'div' )[0];
    var speed = -14 ;
    var target = 0;
    var cssW = parseInt( getStyle( aWrap ).left );
    //向右走
//    !function fn(){
//        cssW += speed ;
//        var t = setAnimation( fn , 13 )
//        if( cssW >= target ){
//            cssW = target;
//            clearAnimation( t )
//        }
//        console.log( cssW );
//        aWrap.style.left = cssW + 'px';
//    }();
    //向左走
//    !function fn(){
//        cssW += speed ;
//        var t = setAnimation( fn , 13 )
//        if( cssW <= target ){
//            cssW = target;
//            clearAnimation( t )
//        }
//        console.log( cssW );
//        aWrap.style.left = cssW + 'px';
//    }();


    //上面2个只有在判断 cssW 是否超出 可以写成通用式
    //思路:
         //判断一下  cssW - target <= speed 是小于speed就会超出 减法可能会出现负数,要加绝对值


    //封装函数
    animation( aWrap ,'left', -14 ,0 );
    function animation( obj , arrt , speed ,target ){
        var cssW = parseInt( getStyle( obj )[arrt] );
        !function fn(){//自执行函数
            cssW += speed;
            var timer = setAnimation(fn);
            if(Math.abs( cssW-target) <= Math.abs(speed) ){  //判断一下  cssW - target <= speed 是小于speed就会超出 减法可能会出现负数,要加绝对值
                clearAnimation(timer);
                cssW = target;
            }
            obj.style[arrt] = cssW+'px';
        }();
    };



    //清除动画兼容写法
    function clearAnimation( t ){
        return window.cancelAnimationFrame ? cancelAnimationFrame( t ):clearTimeout( t )
    }
    //设置动画兼容写法
    function setAnimation( fn , time ){
        return window.requestAnimationFrame ? requestAnimationFrame( fn ):setTimeout( fn , time )
    }

    //获取计算后的样式值兼容写法
    function getStyle( obj ){
        return obj.currentStyle || getComputedStyle( obj )
    }

</script>

相关文章

网友评论

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

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