<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#div1 {
width: 150px;
height: 300px;
background-color: red;
position: fixed;
top: 50px;
left: -150px;
}
#div1 span {
position: absolute;
width: 20px;
height: 60px;
line-height: 20px;
background-color: pink;
right: -20px;
top: 120px;
border-radius: 0 5px 5px 0;
}
</style>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
<script type="text/javascript">
// 获取标签
var oDiv = document.getElementById("div1");
// 事件绑定
oDiv.onmouseover = function() {
startMove(0);
};
oDiv.onmouseout = function() {
startMove(-150);
};
// 运动函数
var timer = null;
function startMove(iTarget) {
var speed = 0;
// 判断速度的正负,控制运动的方向
if(oDiv.offsetLeft > iTarget){
speed = -10;
}else{
speed = 10;
}
// 防止多个定时器同时工作
clearInterval(timer);
timer = setInterval(function() {
// 当运动到目标位置时,停止定时器,否则继续运动
if (oDiv.offsetLeft == iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
}, 20);
}
// 优化1 : 把速度和目标位置,当成参数传给函数
// 优化2 : 把速度干掉,判断目标点和当前位置谁大谁小
</script>
</body>
</html>