两个盒子运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
top: 200px;
}
</style>
<script>
window.onload=function(){
var btn01=document.getElementById("btn01");
var btn02=document.getElementById("btn02");
var btn03=document.getElementById("btn03");
var box1=document.getElementById("box1");
var box2=document.getElementById("box2");
btn01.onclick=function(){
move(box1,400,5);
}
btn02.onclick=function(){
move(box1,400,-10);
}
btn03.onclick=function(){
move(box2,400,10);
}
};
//var timer;这里不能使用全局变量,因为当box1移动时,让box2移动时,box1会停止
//box2关闭了box1的定时器
//创建一个可以执行简单动画的函数
//参数:obj 要执行动画的对象
//speed速度
//target
function move(obj,target,speed){
//关闭上一个定时器
clearInterval(obj.timer);
//开启定时器
obj.timer=setInterval(function(){
//box1.offsetLeft为数值,box1.style.left为字符串
obj.style.left=obj.offsetLeft+speed+"px";
//当元素移动到400px时,使其停止执行动画
//判断box1.style.left是否大于400
if(obj.offsetLeft>target){
obj.style.left=target+"px";
}else if(obj.offsetLeft<0){
obj.style.left=0+"px";
}
}, 50);
}
</script>
</head>
<body>
<button id="btn01">点击按钮以后,box1向右移动</button>
<button id="btn02">点击按钮以后,box1向左移动</button>
<button id="btn03">点击按钮以后,box2向右移动</button>
<br><br><br>
<div id="box1"></div>
<div id="box2"></div>
<div style="width: 0;height: 800px;border-left: 1px black solid;position: absolute;left: 400px;"></div>
</body>
</html>