通过改变属性来实现动画

今天这篇文章主要简述js如何通过改变属性来实现动画效果,比如通过定时器快速改变width, height, left, top等属性,实现图形在html的页面上做匀速的运动。

现在就有这样的一个需求,定义2个不同背景颜色的物体,当点击按钮的时候,实现向左,向下匀速
运动。

关键语法:
1,获取当前dom的指定属性值

function computedStyle(dom,attr) {        
        if(getComputedStyle) {
            return getComputedStyle(dom,'')[attr]
        } else {
            return dom.currentStyle()[attr] //兼容IE
        }
  }

这个方法定义的目的是为了获取dom 属性的值,例如:
dom: '<div width="30px"></div>',调用这个方法
computedStyle(dom,'width') 返回 30。

2,定时器,返回这个定时器的唯一id标识

  timerId = setInterval(function(){
  },1000);

这个定时器的主要目的是为了匀速改变dom的属性的值

示例:

   #box{                
        width: 100px; 
        height: 100px; 
        background: red; 
        position:absolute; 
        /*getComputedStyle 方法取属性左边的值'left' 为800*/
        left: 800px;  
        top: 50px;
    }


    #box1{                
        width: 100px; 
        height: 100px; 
        background: blue; 
        position:absolute; 
        left: 900px; 
        top: 50px;
    }

    <input type="button" id="button" value="开始运动"/>
    <div id="box">box</div>
    <div id="box1">box1</div>

    //封装获取id的方法
    function $(id) {
        return document.getElementById(id);
    }
                
            
    //获取计算后的属性  attr='width'
    function computedStyle(dom,attr) {
        
        if(getComputedStyle) {
            return getComputedStyle(dom,'')[attr]
        } else {
            return dom.currentStyle()[attr]
        }
    }
            
    window.onload=function(){
                
        var btn=$('button');
        
        var box=$('box');
        
        var box1=$('box1');
        
        btn.onclick=function(){
                                
            animate(box,'left',100);
            
            animate(box1,'top',400);
        }
            
        function animate(dom,attr,target){                
                    
                    //多个元素一起运动  每个元素绑定一个属性放当前运动的定时器
                    dom.timer=setInterval(function() {                    
                        var current=parseInt(computedStyle(dom,attr));  
                        var step=(target>current)?1:-1;   
                        /*目标大于当前值 +1  目标小于当前值-1*/                

                        if(target==current) { 
                        // 如果等于100的时候退出,也是定时器退出的条件        
                            dom.style[attr]=target+'px';
                            
                            clearInterval(dom.timer);
                            
                            return false;
                        }
                        //改变位置
                        
                        dom.style[attr]=(current+step)+'px';
                        //改变style的属性,实现动画
                        
                    },10)
                    //每10毫秒改变一次
                }
            }                

猜你喜欢

转载自www.cnblogs.com/jlfw/p/12056001.html
今日推荐