<!DOCTYPE html>
<head>
<title>js速度动画</title>
<meta charset="utf-8">
<style>
*{
margin:0px;
padding:0px;
}
#div1{
width:200px;
height:200px;
background-color:red;
position:relative;
left:-200px;
}
#div1 span{
width:20px;
height:50px;
position:absolute;
left:200px;
top:75px;
background-color:blue;
}
</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');
timer = 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>
有else的时候,进入哪个语句的判断会同时进行,因此方块会在left为0时停下。而当无else的时候,即使left为0取消了定时器,下面位置改变依然会执行