代码如下,其中不会遇到等于目标值,导致动画不会停止。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS速度动画</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
#box{
width: 200px;
height: 200px;
background: red;
position: relative;
left: -200px;
top: 0;
}
#share{
width: 20px;
height: 50px;
background: blue;
position: absolute;
top: 75px;
left: 200px;
color: #fff;
}
</style>
<script type="text/javascript">
var timer = null;
window.onload = function(){
var oBox = document.getElementById('box');
var share = document.getElementById('share');
oBox.onmouseover = function(){
startMove(0);
}
oBox.onmouseout = function(){
startMove(-200);
}
}
function startMove(iTarget){
clearInterval(timer);
var oBox = document.getElementById('box');
var speed = (iTarget - oBox.offsetLeft)/30;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
timer = setInterval(function(){
if (oBox.offsetLeft==iTarget) {
clearInterval(timer);
}else{
oBox.style.left = oBox.offsetLeft+speed+'px';
}
},30)
}
</script>
</head>
<body>
<div id="box"><span id="share">分享</span></div>
</body>
</html>