首页 > 代码库 > Javascript学习------top/left简单动画,效果与jquery的动画差不多

Javascript学习------top/left简单动画,效果与jquery的动画差不多

在网上查看jquery的动画帧率为13毫秒

我用下面的小例子验证了一下:

 1 <!DOCTYPE html> 2 <html> 3 <head> 4     <title>top/left简单动画</title> 5     <style type="text/css"> 6         * { margin: 0px; padding: 0px; } 7     </style> 8     <script src="http://common.cnblogs.com/script/jquery.js"></script> 9 </head>10 <body>11     <div style="width:50px;height:50px;border:1px solid #f36e0a;border-radius:50px;background:#a1fa0e;position:absolute;z-index:1;top:0px;left:0px;" id="dom"></div>12     <div style="width:50px;height:50px;border:1px solid #f36e0a;border-radius:50px;background:#a1fa0e;position:absolute;z-index:1;top:0px;left:52px;" id="dom2"></div>13     <script type="text/javascript">14         var dom = document.getElementById("dom");15         var oldx = parseInt(getStyle(dom, "left").slice(0, -2));16         var oldy = parseInt(getStyle(dom, "top").slice(0, -2));17         var old = { left: oldx, top: oldy };//动画记录json18         var oldover = [];19         var s1 = getss();//动画初始时间毫秒20         21         //动画函数22         function move(movedom, jsons, t) {23             var s2 = getss();//动画进行时间毫秒计算24             var s3 = s2 - s1;//动画耗时差25             s1 = s2;//计录时间此时时间26             var b = s3 / t;//得到动画的相对比例;27             var movelength = 0;28             for (var item in jsons) {//执行动作29                 moveh = jsons[item] * b;30                 if (old[item] >= jsons[item]) {31                     old[item] = jsons[item];32                     oldover.push(0);//放进数组33                 }34                 else {35                     old[item] += moveh;36                 }37                 switch (item) {38                     case "left":39                         dom.style.left = old[item] + "px";40                         break;41                     case "top":42                         dom.style.top = old[item] + "px";43                         break;44                 }45                 movelength++;46             }47             //结束动画;48             if (oldover.length >= movelength) {49                 clearInterval(m);50             }51         }52 53         //获得css值54         function getStyle(obj, attr) {55             return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];56         }57 58         //获得当前时间(毫秒)59         function getss() {60             var dtime = new Date();61             return dtime.getHours() * 3600 * 1000 + dtime.getMinutes() * 60 * 1000 + dtime.getSeconds() * 1000 + dtime.getMilliseconds();62         }63 64         //js动画65         var m = setInterval(move(dom,{top:300,left:300},1000), 13);66         //jquery动画67         $(function () {68             $("#dom2").animate({ top: 300, left: 352 }, 1000, "linear");69         });70     </script>71 </body>72 </html>

 

Javascript学习------top/left简单动画,效果与jquery的动画差不多