明明和老師的代碼是一樣的,為什么我的在多次點(diǎn)擊的時(shí)候還是跑的很快,感覺(jué)前面那個(gè)清除沒(méi)有作用
<!DOCTYPE ?HTML>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js運(yùn)動(dòng)</title>
<style>
*{margin:0px;padding:0px;}
#div1{height:200px;
? ? ? ? ?width:200px;
background:red;
position:relative;
left:-200px;}
#share{width:50px;
? ? ? ?height50px;
? background:blue;
? position:absolute;
? top:100px;
? left:200px;
? }
</style>
<script>
? window.onload=function(){
? var odiv=document.getElementById("div1");
? ? odiv.onmouseover=function(){
startMove();
}
? }
? var timer=null;
? function startMove(){
?clearInterval(timer);
?var odiv=document.getElementById("div1");
?setInterval(function(){
?if(odiv.offsetLeft==0){
?clearInterval(timer);
?}
?else{
?odiv.style.left=odiv.offsetLeft+1+"px";
?}
?},30)
?}
</script>
</head>
<body>
? <div id="div1">
? <span id="share">分享</span>
?</div>
</body>
</html>
2016-04-06
timer在這里需要為全局變量,在定時(shí)器前面加timer=,注意不能再加var,否則據(jù)就近原則,startMove函數(shù)中使用的timer就不是函數(shù)外部的全局變量了,就無(wú)法達(dá)到預(yù)期的效果~你試試看
2016-04-06
你可以試試將setInterval(function(){
?if(odiv.offsetLeft==0){
改為
timer=setInterval(function(){
?if(odiv.offsetLeft==0){
2016-04-06
"clearInterval(timer); " 這句代碼下面還有個(gè) " setInterval(function(){...} " 前面沒(méi)有加 " var timer = "