clearInterval(timer)作用域是怎樣的?
我把mouseout 和mouseover事件執(zhí)行函數(shù)寫成獨(dú)立的2個(gè)函數(shù),但是在mouseout時(shí)間的執(zhí)行函數(shù)內(nèi)最前面如果不寫 clearInterval(timer),mouseout事件不能正常執(zhí)行,請(qǐng)問是什么原因?
我把mouseout 和mouseover事件執(zhí)行函數(shù)寫成獨(dú)立的2個(gè)函數(shù),但是在mouseout時(shí)間的執(zhí)行函數(shù)內(nèi)最前面如果不寫 clearInterval(timer),mouseout事件不能正常執(zhí)行,請(qǐng)問是什么原因?
2017-12-09
舉報(bào)
2017-12-09
//下面是完整代碼,請(qǐng)幫忙看下是什么問題,謝謝!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js 簡(jiǎn)單動(dòng)畫</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
background: orange;
width: 200px;
height: 200px;
position: absolute;
left: -200px;
display: inline-block;
}
span{
display: block;
background: green;
font-family: kaiti;
font-size: 14px;
text-align: center;
vertical-align: center;
line-height: 50px;
width: 35px;
height: 50px;
margin-top: 85px;
position: relative;
left: 200px;
}
</style>
</head>
<body>
<div id="div1"><span id="motion">分享</span></div>
<script type="text/javascript">
var div1=document.getElementById('div1');
var timer=null;
//不同的部分作為參數(shù)傳入,如此就可以把2個(gè)類似的函數(shù)合并成一個(gè)
function startMove(){
? ? ? ? ? clearInterval(timer);
? timer=setInterval(function(){
if(div1.offsetLeft== 0){
? ? ? ? ? clearInterval(timer);}
? ? ? ? ? else
? ? ? ? ?{
div1.style.left=div1.offsetLeft+1+"px";
}
? ?},30);
}
function backMove(){
//clearInterval(timer);//如果刪除這行代碼,mouseout事件就不能正常進(jìn)行
timer=setInterval(function(){
if(div1.offsetLeft== -200){
? ? ? ? ? clearInterval(timer);}
? ? ? ? ? else
? ? ? ? ?{
div1.style.left=div1.offsetLeft-1+"px";
console.log(div1.style.left);
}
? ?},30);
}
div1.addEventListener("mouseover",function(){
startMove(4,0);//前進(jìn)的速度 需要可以整除200
? ? });
div1.addEventListener("mouseout",function(){
startMove(-3,-200); //返回的速度不能大于前進(jìn)的速
? ? });
</script>
</body>
</html>
2017-12-09
你的問題就有問題,關(guān)于定時(shí)器的不應(yīng)該在mouseout里面執(zhí)行不了,可能你的代碼有問題,clearInterval只是清除定時(shí)器,避免上個(gè)定時(shí)器對(duì)下個(gè)的影響。