**<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
}
#box{
width: 100px;
height: 200px;
background-color: #f52b00;
position: relative;
left: -100px;
}
p{
width:30px;
line-height: 30px;
background-color:#df9c1f;
color: #fff;
text-align: center;
position: absolute;
right: -30px;
top: 35px;
}
</style>
</head>
<body>
<div id="box">
<p id = 'ps'>分享到</p>
</div>
<script type = "text/javascript">
//获取div
var box = document.getElementById('box');
//获取p
var ps = document.getElementById('ps');
var timer = null;
//绑定鼠标移入事件
box.onmouseover = function(){ //注意这里的调用方法 一定要放在函数中调用
startMove(0,10)
};
//绑定鼠标移出事件
box.onmouseout = function(){
startMove(-100,-10)
};
//定义空计时器
//将两个函数封装成一个运动函数
function startMove(target,speed){
//清除之前的计时器
clearInterval(timer);
//定义新的计时器
timer = setInterval(function(){
if(box.offsetLeft == target){
clearInterval(timer);
}else {
box.style.left = box.offsetLeft+ speed +'px';
}
},30)
}
// function nextMove(){
//
// //清除之前的计时器
// clearInterval(timer);
// //定义新的计时器
// timer = setInterval(function(){
// if(box.offsetLeft <= -100){
// clearInterval(timer);
// }else {
// box.style.left = box.offsetLeft - 10+'px';
// }
// },30)
// }
</script>
</body>
</html>**
这个模板适用于所有的匀速运动,比如说分享页。