我在做多目标联动时为什么就会出错?
根据《js动画效果》课程中5-1节,我自己实践了一下,发现如果只对单独一个对象做动画可以实现链式动画效果,但一旦对多个对象(比如lis = getElementsByTagName("li")中的每个lis[i])添加动画效果后,鼠标移动到对象上时就会出错。浏览器调试错误截屏如下:
我的html代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>分享栏js动画</title> <script type="text/javascript" src="js/action.js"></script> <style type="text/css"> *{ margin: 0; padding:0; } ul{ margin-top: 30px; list-style: none; } ul li{ width: 200px; height: 50px; background-color: red; margin-bottom: 20px; border:2px solid #000; filter:alpha(opacity:30); opacity: 0.3; } </style> <script type="text/javascript"> window.onload = function(){ var lis = document.getElementsByTagName("li"); var li = document.getElementById("li"); var timer = null;//定义定时器 var alpha = 0; /*li.onmouseover = function(){ startAct(li,"height",100,function(){ startAct(li, "width",400); }); } li.onmouseout = function(){ startAct(li,"width",200,function(){ startAct(li, "height",50); }); }*/ for(var i=0; i<lis.length; i++){ //宽度/高度变化 lis[i].timer = null;//为每个lis对象定义一个timer lis[i].onmouseover = function(){ startAct(this,"height",100,function(){ //alert(1); startAct(this,"width",400); }); } lis[i].onmouseout = function(){ startAct(this,"height",50); } } } </script> </head> <body> <ul> <li id="li"></li> <li></li> <li></li> </ul> </body> </html>
js代码如下(js/action.js):
function startAct(obj,type,iTarget,fn){//obj指作用对象,type指被改变的属性,ITarget指改变的目标值 //初始化清除定时器 clearInterval(obj.timer); var speed = 0;//定义速度 obj.timer = setInterval(function(){ if(type == "alpha"){//如果是透明度变化 if(obj.alpha > iTarget){ speed = -10; }else{ speed = 10; } if(obj.alpha == iTarget){ clearInterval(obj.timer); }else{ obj.alpha = obj.alpha+speed; obj.style.filter = "alpha(opacity:"+obj.alpha+")"; obj.style.opacity = obj.alpha/100; } }else{//如果不是透明度变化 //获取对象容器当前属性的值 var oStyleValue = parseInt(getStyle(obj,type)); //判断速度正负情况下的取值 speed = speed>0 ? Math.ceil((iTarget-oStyleValue)/5) : Math.floor((iTarget-oStyleValue)/5); //判断对象是否运行到目标值 if(oStyleValue == iTarget){ clearInterval(obj.timer); if(fn){ fn(); } }else{ obj.style[type] = oStyleValue + speed +"px"; } } },30); } //获取obj对象某属性当前具体值 function getStyle(obj, type){ if(obj.currentStyle){//IE浏览器 return obj.currentStyle[type]; }else{//Firefox浏览器 return getComputedStyle(obj,false)[type]; } }