栗子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>缓冲动画</title>
<style>
*{margin:0; padding:0;}
#div{
position: relative;
left: -200px;
top: 0;
width: 200px;
height: 200px;
background: orange;
}
#div span{
position: absolute;
left: 200px;
top: 30%;
width: 20px;
height: 50px;
background: red;
}
</style>
</head>
<body>
<div id="div"><span id="share">分享</span></div>
<script>
window.onload = function(){
var div = document.getElementById('div');
div.onmouseover = function(){
startMove(0);
}
div.onmouseout = function(){
startMove(-200);
}
var timer;
function startMove(tagLeft){
clearInterval(timer);
timer = setInterval(function(){
var speed = (tagLeft-div.offsetLeft)/5;
/*
速度 = 距离/时间
速度跟距离成正比,距离大,速度大
Math.ceil(); 向上取整
Math.floor(); 向下取整
*/
speed = speed >0 ? Math.ceil(speed):Math.floor(speed);
// 缓冲运动要判断速度是否大于0,向上取整或者向下取整
if(div.offsetLeft == tagLeft){
clearInterval(timer);
}else{
div.style.left = div.offsetLeft+speed+'px';
}
},30)
}
}
</script>
</body>
</html>