<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>缓冲运动</title>
<style type="text/css">
*{margin: 0;padding: 0;}
#box{width: 200px;height: 200px;background-color: red;position: relative;left: -200px;top: 0;}
#box span{width: 20px;height: 50px;position: absolute;top: 50px;left: 200px;background-color: blue;}
</style>
<script type="text/javascript">
window.onload=function(){
var obox = document.getElementById('box');
obox.onmouseover = function(){
startmove(0);
}
obox.onmouseout = function(){
startmove(-200);
}
}
var timer = null;
function startmove(iTarget){
//clearInterval(timer);
var obox = document.getElementById('box');
// timer = setInterval(function () {
// var speed = (iTarget-obox.offsetLeft)/20;
// speed = speed > 0?Math.ceil(speed):Math.floor(speed);
// if (obox.offsetLeft==iTarget) {
// clearInterval(timer);
// }else{
// obox.style.left = obox.offsetLeft + speed+'px';
// }
// },30)
var speed = (iTarget-obox.offsetLeft)/20;
speed = speed > 0?Math.ceil(speed):Math.floor(speed);
function go() {
if (obox.offsetLeft==iTarget) {
obox.style.left = obox.offsetLeft + iTarget +'px';
} else{
obox.style.left = obox.offsetLeft + speed+'px';
setTimeout(go, 30);
}
}
go();
}
</script>
</head>
<body>
<div id="box"><span>分享</span></div>
</body>
</html>