九种原生js动画效果(5)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>多物体同时运动动画</title> <style type="text/css"> body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,tr,td {margin:0;padding:0; font-size:12px;} table {border-collapse:collapse;border-spacing:0;} fieldset,img {border:0} address,caption,cite,code,dfn,em,strong,th,var {font-style:normal;font-weight:normal} ol,ul {list-style:none} caption,th,td{text-align:center} h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal} q:before,q:after {content:''} abbr,acronym { border:0} .odiv{position:relative;} .odiv ul li{width:200px; height:100px; background:yellow; margin-bottom:20px; border:2px solid #000;} #li1{opacity:0.3;filter:alpha(opacity:30);} </style> </head> <body> <div> <ul> <li></li> </ul> </div> </body> </html> <script language="javascript"> window.onload = function(){ var li1 = document.getElementById('li1'); li1.onmouseover = function(){ startMov(li1,{width:201,height:200,opacity:100}); }; li1.onmouseout = function(){ startMov(li1,{width:200,height:100,opacity:30}); }; li1.timer = null; function startMov(obj,json,fn){//fn回调函数 clearInterval(obj.timer);//执行动画之前清除动画 var flag = true;//是否动画都完成了 obj.timer = setInterval(function(){ for(var attr in json){ var icur = 0; if(attr == 'opacity'){ icur = Math.round(parseFloat(getStyle(obj,attr))*100);//转换成整数,并且四舍五入下 //计算机在计算小数的时候往往是不准确的! } else{ icur = parseInt(getStyle(obj,attr)); } var speed =0; speed = (json[attr] - icur)/8; speed = speed>0?Math.ceil(speed):Math.floor(speed); if(icur != json[attr]){ flag = false; } if(attr == 'opacity'){ obj.style.filter = 'alpha(opacity:'+(icur+speed)+')'; obj.style.opacity = (icur+speed)/100; } else{ obj.style[attr] = icur+speed+'px'; } if(flag){ clearInterval(obj.timer); if(fn){ fn(); } } } },30); } function getStyle(obj,attr) { if(obj.currentStyle){ return obj.currentStyle[attr]; } else{ return getComputedStyle(obj,false)[attr]; } } } //offsetWidth获取的是元素实际的宽度(包括边框和内边距) //只要是多物体运动,所有的属性都不能共用 </script>

最后一个动画效果完善了上述所有动画的代码,自己可以根据上述的代码进行扩展!

其实这九种原生js动画效果,都有独特之处,每个源码都可以直接复制运行,希望对大家掌握js动画有所帮助。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjxwzd.html