运动的最后一课时笔记,感觉蛮难的,有一些东西没有理解,涉及的知识点非常多。
先来看一个小小的东西。关于弹性运动-----设置一个div,当鼠标移上去的时候div伸展开,当鼠标移出的时候div还原到原先的大小。可以复制代码自己运行一下。
iSpeed+=(iTarget-height)/5;
iSpeed*=0.7;
这两句用来设置div运动时的速度,首先加等于实现缓冲效果,其次在第一次的处理之后继续减小速度,乘以一个小于1的数。
if(Math.abs(iSpeed)<1&&Math.abs(iSpeed-height)<1)
{
clearInterval(obj.timer);
obj.style.height=iTarget+'px';
}
else{
height+=iSpeed;
obj.style.height=height+'px';
}
如果速度小于1,并且距离小于1,那么就清除定时器;同时硬性的设置div的高度为目标值;相反地,就运行定时器。
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>无标题文档</title> 6 <style> 7 #div1{width:100px;height:50px;background:#666;} 8 </style> 9 <script> 10 window.onload=function(){ 11 var oDiv=document.getElementById('div1'); 12 oDiv.onmouseover=function(){ 13 startMove(oDiv,100); 14 }; 15 oDiv.onmouseout=function(){ 16 startMove(oDiv,50); 17 }; 18 } 19 20 var iSpeed=0; 21 var height=50; 22 23 function startMove(obj,iTarget){ 24 clearInterval(obj.timer); 25 obj.timer=setInterval(function(){ 26 iSpeed+=(iTarget-height)/5; 27 iSpeed*=0.7; 28 if(Math.abs(iSpeed)<1&&Math.abs(iSpeed-height)<1) 29 { 30 clearInterval(obj.timer); 31 obj.style.height=iTarget+'px'; 32 } 33 else{ 34 height+=iSpeed; 35 obj.style.height=height+'px'; 36 } 37 },30); 38 39 } 40 </script> 41 </head> 42 43 <body> 44 <div id="div1"></div> 45 </body> 46 </html>