动画开关

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>动画开关</title>
    <style type="text/css">
        *{margin:0;padding:0;}
        body{position:relative;}
        div{width: 100px;height: 100px;background: pink;margin:50px;left:50px;position: absolute;}
    </style>
    <script type="text/javascript">

        window.onload=function(){
            var oBtn1=document.getElementById("btn1");
            var oBtn2=document.getElementById("btn2");
            var oBox=document.getElementById("box");
            //timer=null;

            //oBox.timer=null;

            // oBtn2.onclick=function(){
            //     clearInterval(oBox.timer);
            //     oBox.timer=setInterval(function(){
            //         var speed=parseInt(getStyle(oBox,"left"))+10;
            //         if(speed>800){
            //             speed=800;
            //         };


            //         oBox.style.left=speed+"px";
            //         if(speed==800){
            //             clearInterval(oBox.timer);
            //             alert(speed);
            //         };
            //     },20);
            // };
            //
            //
            oBtn1.onclick=function(){
                doMove(oBox,-12,-10)
            };


            oBtn2.onclick=function(){
                doMove(oBox,12,800)
            };

            function doMove(obj,dir,target){
                clearInterval(obj.timer);
                obj.timer=setInterval(function(){
                    var speed=parseInt(getStyle(obj,"left"))+dir;
                    if(speed>target && dir>0){
                        speed=target;
                    };

                    if(speed<target && dir<0){
                        speed=target;
                    };


                    obj.style.left=speed+"px";
                    if(speed==target){
                        clearInterval(obj.timer);
                    };
                },20);
            };




            function getStyle(obj,attr){return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];}
        };
    </script>
</head>
<body>
    <input id="btn1" type="button" value="后"/>
    <input id="btn2" type="button" value="前"/>
    <div id="box"></div>
</body>
</html>

posted on 2017-04-24 15:59  37℃的冰  阅读(112)  评论(0)    收藏  举报

导航