原生js仿jquery--animate效果

效果

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动画</title>
    <style>
        *{margin:0;padding:0;}
        .box{width: 400px;height: 300px;background: #000;margin:40px auto;color: #fff;font-size: 18px;text-align: center;}
    </style>
    <script>
    //获取对象样式规则信息,IE下使用currentStyle
    function getStyle(obj,style){
        return obj.currentStyle?obj.currentStyle[style]:getComputedStyle(obj,false)[style];
    }
    //原生js动画相似jquery--animate
    function animate(obj,styleJson,callback){
        clearInterval(obj.timer);
        // 开启定时器
        obj.timer=setInterval(function(){
            var flag=true;//假设全部动做都已完成成立。
            for(var styleName in styleJson){
                //1.取当前属性值
                var iMov=0;
                // 透明度是小数,因此得单独处理
                iMov=styleName=='opacity'?Math.round(parseFloat(getStyle(obj,styleName))*100):parseInt(getStyle(obj,styleName));

                //2.计算速度
                var speed=0;
                speed=(styleJson[styleName]-iMov)/8;//缓冲处理,这边也能够是固定值
                speed=speed>0?Math.ceil(speed):Math.floor(speed);//区分透明度及小数点,向上取整,向下取整
                
                //3.判断是否到达预约值
                if(styleJson[styleName]!=iMov){
                    flag=false;
                    if(styleName=='opacity'){//判断结果是否为透明度
                        obj.style[styleName]=(iMov+speed)/100;
                        obj.style.filter='alpha(opacity:'+(iMov+speed)+')';
                    }else{
                      obj.style[styleName]=iMov+speed+'px';
                    }
                }
            }
            if(flag){//到达设定值,中止定时器,执行回调
                clearInterval(obj.timer);
                if(callback){callback();}
            }
        },30)
    }
    window.onload=function(){
        document.getElementById('box').onclick=function(){
            var oThis=this;
            animate(oThis,{'width':'500'},function(){
                animate(oThis,{'height':'400'},function(){alert('宽度高度都增长了')});
            });
        }
        
    }
    
    </script>
</head>
<body>
    <div class="box" id="box">点击效果:宽度增长->高度增长->弹出框</div>
</body>
</html>

注意点

1.动画前要先中止原来的定时器,否则绑定多个对象的话会冲突javascript

2.定时器的id要区分开,不能重叠,这里我直接那绑定对象的 对象来赋值  obj.timercss

3.要判断所要执行的动画,是否所有到了设定值=> flag,所有执行完再中止定时器再执行回调函数html

4.javascript的数据类型转换问题java

alert(0.07*100);
//弹出7.000000000000001

注意:Javascript在存储时并不区分number和float类型,而是统一按float存储。而javascript使用IEEE 754-2008 标准定义的64bit浮点格式存储number,按照IEEE 754的定义:jquery

decimal64对应的整形部分长度为 10,小数部分长度为16,因此默认的计算结果为“7.0000000000000001”,如最后一个小数为0,则取1做为有效数字标志。css3

5.传入的json数据不能带px,例如{'width':'300px'},为了兼容透明度的数值,没想到好的处理方式,有没有大神指导下...json

6.该定时器作了缓冲处理,变化愈来愈慢,想要快速的效果或者匀速的效果,只须要在2.计算速度那块作下处理就能够浏览器

7.不兼容css3的属性,只兼容了(width,height,top,left,right,bottom,opacity)函数

8.获取对象样式的信息,要判断IE或者火狐浏览器,区别对待动画

相关文章
相关标签/搜索