*{margin:0;padding:0;} 為什么不寫這個,就停不下來了?
<!DOCTYPE html>
<html>
<head>
<title>動畫</title>
<style type="text/css">
#box{
width: 200px;
height: 100px;
background-color: black;
position: relative;
left:-200px;
}
#share{
width: 30px;
height: 50px;
background-color: blue;
position: absolute;
left:200px;
}
</style>
</head>
<body>
<div id="box"><span id="share"></span></div>
<script type="text/javascript">
window.onload=function(){
var odiv=document.getElementById('box');
odiv.onmouseover=function(){
startMove();
}
var timer=null;
function startMove(){
timer=setInterval(function(){
if(odiv.offsetLeft==0){
clearInterval(timer);
}
else{
odiv.style.left=odiv.offsetLeft+10+'px';
}
},30)
}
}
</script>
</body>
</html>
2018-03-25
跟css中的{margin:0;padding:0;} 沒有關(guān)系,你的代碼中,判斷offsetLeft 的條件改為: if(odiv.offsetLeft>=0) ?它就停下來了 ,因為在不斷移動的過程中,不一定有0這個值
還有一個問題,進入startMove()時, 需要先清除一下定時器,目的是保證同時只有一個定時器在運行,你的代碼還給你,就改了兩個地方:
<!DOCTYPE html>
<html>
<head>
<title>動畫</title>
<style type="text/css">
#box{
width: 200px;
height: 100px;
background-color: black;
position: relative;
left:-200px;
}
#share{
width: 30px;
height: 50px;
background-color: blue;
position: absolute;
left:200px;
}
</style>
</head>
<body>
<div id="box"><span id="share"></span></div>
<script type="text/javascript">
window.onload = function() {
? ? var odiv = document.getElementById('box');
? ? odiv.onmouseover = function() {
? ? ? ? startMove();
? ? }
? ? var timer = null;
? ? function startMove() {
? ? ? ? clearInterval(timer); ? ? ? ? ? ? ? ?// debug ?1
? ? ? ? timer = setInterval(function() {
? ? ? ? ? ? console.log(odiv.offsetLeft)
? ? ? ? ? ? if (odiv.offsetLeft >= 0) { ? ? ?// ?debug 2
? ? ? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? odiv.style.left = odiv.offsetLeft + 10 + 'px';
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? 300)
? ? }
}
</script>
</body>
</html>