<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS动画的学习</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
#div_share {
width: 200px;
height: 200px;
position: relative;
background-color: red;
left: -200px;
top: 200px;
}
#span_share {
width: 20px;
height: 40px;
background-color: blue;
position: absolute;
left: 200px;
top: 75px;
}
</style>
<body>
<div id="div_share">
<span id="span_share">分享</span>
</div>
<script type="text/javascript">
window.onload = function() {
var div_share = document.getElementById("div_share"); //快捷键:geti=getElementById
div_share.onmouseover = function() {
startMove(0);
}
div_share.onmouseout = function() {
startMove(-200);
}
var timmer = null;
function startMove(target) { //快捷键:fn 新建一个方法
clearInterval(timmer); //先清除以上的定时器
var div_share = document.getElementById("div_share"); //快捷键:geti=getElementById
//错误的地方timer = setInterval(function() { //快捷键:si 新建一个定时器
timmer = setInterval(function() { //快捷键:si 新建一个定时器
var speed = 0;
speed = div_share.offsetLeft > target ? -10 : 10;//三目运算比if else来的简单多了
if (div_share.offsetLeft == target) {
clearInterval(timmer);
} else {
div_share.style.left = div_share.offsetLeft + speed + "px";
}
}, 30);
}
}
</script>
</body>
</html>