JS 缓冲运动 带运动的留言本 小案例
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> 3 4 <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <title>3.带运动效果的留言本</title> 8 <meta name="author" content="Administrator" /> 9 <!-- Date: 2014-12-11 --> 10 <style> 11 *{margin:0;padding:0} 12 textarea{border:1px solid #000;} 13 ul{overflow:hidden;width:500px;height:500px;padding:10px; border:1px solid #000; position:absolute;right:300px;top:0} 14 li{list-style:none;line-height:28px;border-bottom:1px solid #ccc;overflow:hidden} 15 </style> 16 <script> 17 window.onload=function(){ 18 var oTxt=document.getElementsByTagName('textarea')[0]; 19 var oBtn=document.getElementById('btn'); 20 var oUl=document.getElementsByTagName('ul')[0]; 21 oBtn.onclick=function(){ 22 var oLi=document.createElement('li'); 23 oLi.innerHTML=oTxt.value; 24 oUl.appendChild(oLi); 25 oTxt.value=''; 26 27 //这里要先将oLi的offsetHeight存起来,然后再设置初始化高度为0,如果顺序反了将不起作用,那么就是先设为0,再获取高度了 28 var iHnow=parseInt(css(oLi,'height')); //parseInt 将字符串类型转化为数字类型 29 oLi.style.height='0px'; 30 31 huanchong(oLi,{ 32 'height':iHnow 33 }) 34 } 35 } 36 function css(obj,attr) { 37 return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr] 38 } 39 function huanchong(obj,json,fn){ 40 clearInterval( obj.timer ); 41 obj.timer=setInterval(function(){ 42 43 var iBtn=true; 44 45 for(var attr in json){ 46 var iTarget = json[attr]; 47 48 if(attr == 'opacity' ){ 49 var iSpeed = (iTarget-Math.round((css(obj,attr)*100)))/6; 50 }else{ 51 var iSpeed = (iTarget-parseInt(css(obj,attr)))/6; 52 } 53 54 iSpeed= iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); //精确值 55 56 if(attr == 'opacity' ){ 57 var s=Math.round(css(obj,attr)*100) + iSpeed; 58 }else{ 59 var s=parseInt(css(obj,attr)) + iSpeed; 60 } 61 62 if( s > iTarget && iSpeed > 0 || s < iTarget && iSpeed < 0) s=iTarget; 63 64 if( s!= iTarget ){ 65 iBtn=false; 66 if(attr == 'opacity' ){ 67 obj.style[attr] = s/100; 68 obj.style.filter='alpha(opacity='+s+')' 69 }else{ 70 obj.style[attr] = s +'px'; 71 } 72 } 73 74 } 75 if( s!= iTarget ){ 76 iBtn=true; 77 fn && fn.call(obj) 78 } 79 },30) 80 } 81 </script> 82 </head> 83 <body> 84 <textarea id="text" rows="10" cols="40"></textarea> 85 <input type="button" id="btn" value='留言'/> 86 <ul> </ul> 87 </body> 88 </html>