<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>分享</title>
<style>
body,div,span{
margin:0;
padding:0;
}
.div{
background:red;
width:200px;
height:200px;
position:relative;
left:-200px;
top:10px; }
.a{
padding:2px;
width:20px;
height:50px;
position:absolute;
left:200px;
top:20px;
background:blue;
color:white;
text-decoration:none;
}
</style>
<script>
window.onload = function (){
var div = document.getElementById('div');
div.onmouseover = function (){
display(10,0);
}
div.onmouseout = function (){
display(-10,-200);
}
}
var stop = null;
function display(speed, targetLeft){
clearInterval(stop);
var div = document.getElementById('div');
stop = setInterval(function(){
if(div.offsetLeft == targetLeft){
clearInterval(stop);
}
else{
div.style.left = div.offsetLeft + speed + 'px';
}
}, 30);
}
</script>
</head> <body>
<div class="div" id="div">
<a href="#" class="a" id="a">分享</a>
</div> </body>
</html>
动画总结:写js函数时,如果两个函数差不多,可以把相同的地方提出来当参数穿进去。对于计时器要想到清空它。