為什么按照老師說的將移進移除的代碼合并為一個,提出參數(shù)傳入后執(zhí)行沒反應(yīng)?謝謝
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS動畫</title>
<style type="text/css">
body,div,span{
margin: 0;
padding: 0;
}
#div1{
width: 200px;
height: 200px;
background: pink;
position: relative;
left: -200px;
top:0;
}
#div1 span{
width: 20px;
height: 50px;
background:yellow ;
position: absolute;
left: 200px;
top:75px;
}
</style>
<!--利用計時器,加上控制元素位置,實現(xiàn)運動效果-->
<script >
window.onload=function(){
var oDiv=document.getElementById('div1')
oDiv.onmouseover=function(){
startMove(10,0);
}
oDiv.onmouseout=function(){
startMove(-10,-200);
}
}
var timer=null;
//兩個代碼很相似,可以合并為一個,把不同的部分作為參數(shù)提出來
// ? ?function startMove(){ ?
// ?clearInterval(timer) ? ? ? ?//一進來先把定時器清理掉,避免打開多個定時器使速度家加快
// ?var oDiv=document.getElementById('div1')
// ?timer=setInterval(function(){
// ?if(oDiv.offsetLeft==0){clearInterval(timer)}
? // ? ? ? ? ? ? ? else{oDiv.style.left=oDiv.offsetLeft+1+'px'}
// ? ? ?},30)
// }
? // ? ? ? function startMove1(){ ?
// ?clearInterval(timer) ? ? ? ?//一進來先把定時器清理掉,避免打開多個定時器使速度家加快
// ?var oDiv=document.getElementById('div1')
// ?timer=setInterval(function(){
// ?if(oDiv.offsetLeft==-200){clearInterval(timer)}
? // ? ? ? ? ? ? ? else{oDiv.style.left=oDiv.offsetLeft-1+'px'}
// ? ? ?},30)
// }
? ?
? ? ? function startMove(speed,iTarget){ ?
clearInterval(timer) ? ? ? ?//一進來先把定時器清理掉,避免打開多個定時器使速度家加快
var oDiv=document.getElementById('div1')
timer=setInterval(function(){
if(oDiv.offsetLeft==iTarget){clearInterval(timer)}
? ? ? ? ? ? ? ? else{oDiv.style.left=oDiv.offsetLeft+speed+'px'}
? ?},30)
</script>
</head>
<body>
<div id="div1"><span id="share">分享</span></div>>
</body>
</html>
2018-01-09
</script>前面少了}