《js动画效果》之链式运动

学习视频资源来自慕课网《js动画效果》:http://www.imooc.com/learn/167。

根据视频所讲,所谓链式运动,即多个动画效果依次发生,eg: 让一个物体先变宽,然后变高。这节课程的代码实现建立在前几节课程的基础上,要实现链式运动的关键点是回调函数的使用,下面的重点即是如何实现回调。练习代码如下:

<!DOCTYPE html>
 <html>
 	<head>
 		<meta charset="utf-8">
 		<style type="text/css">
 		*{
 			padding:0;
 			margin:0;
 		}
 		ul li{
 			list-style:none;
 			width:200px;
 			height:100px;
 			background:green;
 			margin:20px;
 			border:2px #ccc solid;
 			filter:alpha(opacity:30);
 			opacity:0.3;
 		}
 		</style>
 		<script type="text/javascript">
 			window.onload = function(){
 				var testLi = document.getElementById("testLi");
 				testLi.onmouseover = function(){
 					playFun(testLi, 300, "height", function(){//回调
 						playFun(testLi, 400, "width", function(){//回调
 							playFun(testLi, 100, "opacity");
 						});
 					});</span>
 				};
 				testLi.onmouseout = function(){
 					playFun(testLi, 30, "opacity", function(){//回调
 						playFun(testLi, 200, "width", function(){//回调
 							playFun(testLi, 100, "height");
 						});
 					});</span>
 				}

 				function playFun(obj,itarget,attr,fn){//fn——回调函数
					clearInterval(obj.timer);
					obj.timer = setInterval(function(){
						var getValue = 0;
						if(attr == "opacity"){

							//parseFloat返回小数值
							//由于计算机存储小数有误差,采用Math.round()四舍五入得整数
							getValue = Math.round(parseFloat(getStle(obj,attr))*100);
						}else{
							getValue = parseInt(getStle(obj,attr));
						}
						
						var speed = (itarget - getValue)/10;
						speed = speed>0?Math.ceil(speed):Math.floor(speed);
						
						//判断运动是否结束
						if(getValue == itarget){
							clearInterval(obj.timer);
							if(fn){//动画结束后判断是否调用回调函数,存在即执行
								fn();
							}
						}else{
							//obj.style[attr],采用中括号传参
							if(attr == "opacity"){
								getValue += speed;
								obj.style["filter"] = "alpha(opacity:"+ getValue +")";
								obj.style["opacity"] = getValue/100;
							}else{
								obj.style[attr] = getValue + speed + "px";
							}
							
						}
					},50);
				}

				//获取属性值
				function getStle(ele,attr){ 
					if(ele.currentStyle){ //兼容IE浏览器
						return ele.currentStyle[attr];
					}else{  //兼容firefox浏览器
						return getComputedStyle(ele,false)[attr];
					}
				}
 			}
 		</script>
 	</head>
 	<body>
 		<ul>
 			<li id="testLi"></li>
 		</ul>
 	</body>
 </html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值