运动框架:
- 先要清除定时器,防止多次点击或者移入移出时,开启多个定时器,元素的运动会是所有定时器中运动的总和
- 当达到目的时,要清除定时器(使用if/else 实现)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<style>
#div1{
width:150px;
height:200px;
background:#3271E5;
left :-150px;
top:150px;
position: absolute;
}
#div1 span{
width: 20px;
height:40px;
right:-20px;
top:80px;
background:red;
text-align:center;
line-height:20px;
display:block;
position: absolute;
}
</style>
<script>
window.οnlοad=function(){
var oDiv=document.getElementById('div1');
var timer=null;
var speed;
oDiv.οnmοuseοver=function(){
startMove(0);
};
oDiv.οnmοuseοut=function(){
startMove(-150);
};
function startMove(itarget){
clearInterval(timer);
if(oDiv.offsetLeft<itarget)
{
speed=10;
}
else
{
speed=-10;
}
timer=setInterval(function(){
if(oDiv.offsetLeft==itarget)
{
clearInterval(timer);
}
else
{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},30);
}
};
</script>
</head>
<body>
<div id="div1">
<span>分享</span>
</div>
</body>
</html>
运行结果图: