这段代码中 方法一:用的setInterval( )定时器 作小球移动 , 若再次点击按钮小球移动速度会比上一次快;
方法二:用的setInterTimeout() 再次点击按钮 ,若要让他保持原来的速度需要在setTimeout()定时器上方清除这个定时器,以防再次点击带来影响。
方法三:小球加速运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#box{width: 100px;height: 100px;border-radius: 50%;background: skyblue;position: absolute;left: 0;top: 100px;}
#wall{width: 2px;height:500px;position: absolute;left: 500px;background: #000;}
</style>
</head>
<body>
<button id="btn">开始</button>
<div id="box"></div>
<div id="wall"></div>
<script type="text/javascript">
//方法一
var o=document.getElementById("box");
var speed=2;//小球移动距离
var c; //定义一个变量用来盛放定时器
//点击开始按钮小球开始移动
document.getElementById('btn').onclick=function(){
move();
}
//小球移动
function move(){
var m=getComputedStyle(o,null).left;
m=parseInt(m);
o.style.left=m+speed+"px";
clearTimeout(c);//再次点击按钮小球的速度不会加快
if (m>=400) {
clearTimeout(c);
}else{
c=setTimeout(move,10);
}
}
/*
//方法二
//多次点击按钮小球速度会加快
var o=document.getElementById("box");
var speed=2;//小球移动距离
var c; //定义一个变量用来盛放定时器
//点击开始按钮小球开始移动
document.getElementById('btn').onclick=function(){
// clearInterval(c);//多个按钮多个方向多个定时器时需要清除定时器带来的影响
var c=setInterval(move2,10)
}
//小球移动2
function move2(){
var m=window.getComputedStyle(o,null).left;
m=parseInt(m);
if (m>=400) {
clearInterval(c);
}else{
o.style.left=m+speed+"px";
}
}*/
/*//方法三 小球加速运动
var o=document.getElementById("box");
var speed=2;//小球移动距离
var c; //定义一个变量用来盛放定时器
//点击开始按钮小球开始移动
document.getElementById('btn').onclick=function(){
setInterval(move,50);
}
function move(){
//获取小球左边距离
var m=window.getComputedStyle(o,null).left;
m=parseInt(m);
// if (m>=400) {
// clearInterval(c);
// }else{
//给小球左边赋予新值
o.style.left=m+speed+"px";
// }
setTimeout(move,500)
}*/
</script>
</body>
</html>