匀速运动:
1、设置定时器,每隔一段时间更改位置,达到匀速运动
2、设置定时器前需清除定时器,以防多次触发重复生成多个定时器
3、当运动位置达到目标值时,可通过清除定时器停止运动clearInterval()
4、当定义函数多处相同时,可封装为一个函数,用不同参数调用,尽量少传递相同的参数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
*{
margin: 0;
padding: 0
;}
#one{
height:200px;width:200px;
background-color: blueviolet;
position: relative;
left: -200px;
}
#two{
height:50px;
width: 50px;
background: red;
position: absolute;
}
</style>
<script>
window.onload=function(){
var b=document.getElementById("two");
b.onmouseover=function(){//鼠标移入时移动出来
startMove(0);
}
b.onmouseout=function(){
startMove(-200);
}
}
//随计时器函数时移动
var timer=null;
var speed=0;
function startMove(iTarget){
clearInterval(timer);//-------------------------2
var a=document.getElementById("one");
if(iTarget>a.offsetLeft){
speed=10;
}else{
speed=-10;
}
timer=setInterval(function(){if(a.offsetLeft==iTarget){
clearInterval(timer);//-------------3
}else
{a.style.left=a.offsetLeft+speed+'px';}
},30)---------------------------------------1
}
</script>
</head>
<body>
<div id="one">
</div>
<div id="two">
<span>分享</span>
</div>
</body>
</html>