为了账号安全,请及时绑定邮箱和手机立即绑定

关于回调函数为什么不能直接将执行的函数作为参数而要嵌套一个匿名函数?

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<style type="text/css">
		ul,li{
			list-style: none;
		}
		ul li{
			width: 200px;
			height: 100px;
			background: red;
			margin-bottom: 20px;
			border: 4px solid #000;
			font-size: 8px;
			filter: alpha(opacity:30);
			opacity: 0.3;
		}
	</style>
	<script type="text/javascript">
		window.onload=function(){
			var li1=document.getElementById("li1");
			li1.timer=null;
			li1.onmouseover=function(){
				startMove(li1,400,'width',startMove(li1,200,'height'));
			}
				li1.onmouseout=function(){
					startMove(li1,200,'width',startMove(li1,100,'height'));
			}
		}
		function startMove(obj,iTarget,attr,fn){
			clearInterval(obj.timer);
			obj.timer=setInterval(function(){
				var icur=0;
				if(attr=='opacity'){
					icur=Math.round(parseFloat(getStyle(obj,attr))*100);
					
				}
				else{
					icur=parseInt(getStyle(obj,attr))
				}
				var speed=(iTarget-icur)/10;
					speed=speed>0?Math.ceil(speed):Math.floor(speed);
					if(icur==iTarget)
						{clearInterval(obj.timer);
							if(fn) {fn();}
						}
					else{
						if (attr=='opacity') {obj.style[attr]=(icur+speed)/100;}
						else {obj.style[attr]=icur+speed+'px';} }
		},20);
		}
		function getStyle(obj,attr){
			if(obj.currentStyle){
				return obj.currentStyle[attr];
			}
			else{
				return getComputedStyle(obj,false)[attr];
			}
		}
	</script>
</head>  
<body>
<ul>
	<li id="li1"></li>
</ul>
</body>
</html>

求解关于回调函数为什么不能直接将执行的函数作为参数而要嵌套一个匿名函数?

正在回答

1 回答

看了半天才弄明白你的意思:

startMove(li1,400, 'width', startMove(li1,200,'height'));

startMove(li1,200,'height')意思是立即执行这个函数,这是一个执行的动作,不能作为参数传递。

startMove(li1,400, 'width', function(){startMove(li1,200,'height')});

function(){startMove(li1,200,'height')}是定义一个匿名函数,函数内随便执行什么。


不知道我这样有没有说清楚

3 回复 有任何疑惑可以回复我~
#1

徐锦杰 提问者

非常感谢!
2017-03-08 回复 有任何疑惑可以回复我~
#2

徐锦杰 提问者

明白了,3q
2017-03-08 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

关于回调函数为什么不能直接将执行的函数作为参数而要嵌套一个匿名函数?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信