点击以后#div是瞬间移动的.如果改成下面这样:
$("div").style.left = i +"px";
$("div").style.top = i +"px";
timer = setTimeout(aa,130);
就正常了..
问题都在aa.apply(this) 这句身上.
请问 aa.apply(this)是怎么工作原理的?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#ul{ margin:0;padding:0;list-style:none;position:fixed;bottom:10px;left:50%; margin-left:-250px}
#ul li{ float:left;width:100px;height:100px;background:orange;margin-right:5px}
#div{ width:100px;height:100px;position:absolute;top:0;left:0;background:orange; }
</style>
</head> <body>
<div id="div"></div>
<script type="text/javascript">
var $ = function(id){return typeof id === 'string'?document.getElementById(id):id}
var log = function(info){ return console.log(info) }
$("div").onclick = aa;
var i = 0;
var timer;
function aa(){
log(this)
if(i < 120){
i++;
this.style.left = i +"px";
this.style.top = i +"px";
timer = setTimeout(aa.apply(this),130);
}else{
clearTimeout(timer)
}
}
</script> </body>
</html>
$("div").style.left = i +"px";
$("div").style.top = i +"px";
timer = setTimeout(aa,130);
就正常了..
问题都在aa.apply(this) 这句身上.
请问 aa.apply(this)是怎么工作原理的?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#ul{ margin:0;padding:0;list-style:none;position:fixed;bottom:10px;left:50%; margin-left:-250px}
#ul li{ float:left;width:100px;height:100px;background:orange;margin-right:5px}
#div{ width:100px;height:100px;position:absolute;top:0;left:0;background:orange; }
</style>
</head> <body>
<div id="div"></div>
<script type="text/javascript">
var $ = function(id){return typeof id === 'string'?document.getElementById(id):id}
var log = function(info){ return console.log(info) }
$("div").onclick = aa;
var i = 0;
var timer;
function aa(){
log(this)
if(i < 120){
i++;
this.style.left = i +"px";
this.style.top = i +"px";
timer = setTimeout(aa.apply(this),130);
}else{
clearTimeout(timer)
}
}
</script> </body>
</html>
setTimeout(aa.apply(this),130);aa.apply会调用aa函数,而在aa函数中又回调用aa.apply,无限递归,所以是瞬移的情况,而aa.apply是有的返回值是undefinded。所以设置可以通过。