clearInterval(timer)作用域是怎樣的?
我把mouseout 和mouseover事件執行函數寫成獨立的2個函數,但是在mouseout時間的執行函數內最前面如果不寫 clearInterval(timer),mouseout事件不能正常執行,請問是什么原因?
我把mouseout 和mouseover事件執行函數寫成獨立的2個函數,但是在mouseout時間的執行函數內最前面如果不寫 clearInterval(timer),mouseout事件不能正常執行,請問是什么原因?
2017-12-09
舉報
2017-12-09
//下面是完整代碼,請幫忙看下是什么問題,謝謝!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js 簡單動畫</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;
//不同的部分作為參數傳入,如此就可以把2個類似的函數合并成一個
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事件就不能正常進行
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);//前進的速度 需要可以整除200
? ? });
div1.addEventListener("mouseout",function(){
startMove(-3,-200); //返回的速度不能大于前進的速
? ? });
</script>
</body>
</html>
2017-12-09
你的問題就有問題,關于定時器的不應該在mouseout里面執行不了,可能你的代碼有問題,clearInterval只是清除定時器,避免上個定時器對下個的影響。