昨日TX上机+面试,无奈又输在时间和平时的细节积累上了,废话不多说,直接上这道让我悲剧了的题目:
实现一个DIV动画效果,DIV移动从快到慢,最后停止,时间为5s。
咋来审题,其实需要实现这个效果是相当简单的,但是毕竟是亲身上机,无奈上机使用的编辑器也没有js的智能提示(平时习惯太坏),所以各方面因素 ,这道题终究迫于时间问题而未完成,这里做个笔记,来了却自己当时的做题思路,代码奉上:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <title>Animation Test</title> 5 <style type="text/css"> 6 * { 7 margin: 0; 8 padding: 0; 9 } 10 11 #demo { 12 position: absolute; 13 left: 0px; 14 top: 0px; 15 width: 100px; 16 height: 100px; 17 background-color: #aaf; 18 } 19 </style> 20 </head> 21 <body> 22 <div id="demo"></div> 23 <script type="text/javascript"> 24 (function(window){ 25 "use strict"; 26 var timer, 27 demo; 28 29 timer = { 30 id: null, 31 fns: [], 32 delay: 1000 / 60, 33 loop: function(){ 34 var i, 35 l, 36 fns; 37 fns = timer.fns; 38 for(i = 0, l = fns.length; i < l; i++){ 39 if(fns[i]() === false){ 40 fns.splice(i, 1); 41 i--; 42 l--; 43 } 44 } 45 if(fns.length <= 0){ 46 timer.stop(); 47 } 48 }, 49 start:function(){ 50 if(this.id !== null){ 51 return; 52 } 53 this.id = window.setInterval(this.loop, this.delay); 54 }, 55 stop:function(){ 56 if(this.id === null){ 57 return; 58 } 59 window.clearInterval(this.id); 60 }, 61 add:function(func){ 62 if(typeof func !== "function"){ 63 return; 64 } 65 this.fns.push(func); 66 this.start(); 67 } 68 }; 69 70 demo = { 71 o: document.getElementById("demo"), 72 speed: 5, 73 startTime: null, 74 duration: 5000, 75 now: function(){ 76 return (new Date()).getTime(); 77 }, 78 setOffsetX:function(x){ 79 this.o.style.left = x + "px"; 80 }, 81 getOffsetX: function(){ 82 return parseFloat(this.o.style.left) || 0; 83 }, 84 step:function(){ 85 var x; 86 if(demo.now() > demo.startTime + demo.duration){ 87 return false; 88 } 89 x = demo.getOffsetX(); 90 demo.speed = 5 * (1 - (demo.now() - demo.startTime) / demo.duration); 91 demo.setOffsetX(x + demo.speed); 92 }, 93 doTest:function(){ 94 if(this.startTime !== null){ 95 return; 96 } 97 this.startTime = this.now(); 98 timer.add(this.step); 99 } 100 }; 101 102 demo.doTest(); 103 })(window); 104 </script> 105 </body> 106 </html>
代码中构建了两个对象,一个timer为时间定时器,一个demo对象控制动画,核心思想是让DIV移动时,他的speed逐步衰减(与剩余时间有关,按剩余时间除以总时间来算百分比),效果大家自己COPY代码演示即可。
不管怎样,半个多月了,经历大大小小的各种面试,学到了许多东西。睡觉了,今天又要继续找工作咯 ; )