為什么timer必須聲明在函數(shù)外面(附代碼)?
timer直接在函數(shù)里聲明使用的話會有bug,放在外面就沒事了,求解
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>緩沖運(yùn)動(dòng)</title>
<style type="text/css">
*{border:0; margin:0;}
#div1{ width:200px; height:200px; background:red; position:relative; top:0; left:-200px;}
.div2{ width:20px; height:40px; background:blue; position:absolute; top:80px; left:200px;}
</style>
<script type="text/javascript">
window.onload=function(){
var div1=document.getElementById("div1");
div1.onmouseover=function(){
startMove(0);
}
div1.onmouseout=function(){
startMove(-200);
}
var timer=null;
function startMove(target){
clearInterval(timer);
timer=setInterval(function(){
var speed=(target-div1.offsetLeft)/20;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(target==div1.offsetLeft){
clearInterval(timer);
}else{
div1.style.left=div1.offsetLeft+speed+"px";
}
},30);
}
}
</script>
</head>
<body>
<div id="div1"><div class="div2"></div></div>
</body>
</html>
2016-01-04
函數(shù)體中的局部變量只在函數(shù)執(zhí)行時(shí)生成的調(diào)用對象中存在,函數(shù)執(zhí)行完畢時(shí)局部變量即刻銷毀。就是說你的函數(shù)執(zhí)行到開啟定時(shí)器以后,就算執(zhí)行結(jié)束了,那么這個(gè)局部變量就會被銷毀。也就是說剛打開定時(shí)器,定時(shí)器就沒了
2016-01-03
聲明在外邊 ?是作為一個(gè)全局變量,那樣你在任何function里面都可以調(diào)用,如果你是聲明在function里面就成了局部變量,只能在聲明的function里面來使用,其他function調(diào)用不到這個(gè)變量,所以會報(bào)錯(cuò)。