点击按钮之前:
点击按钮之后:运动到400处,停下。
<!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;
}
</style>
<script>
window.onload=function(){
var btn01=document.getElementById("btn01");
var btn02=document.getElementById("btn02");
var box1=document.getElementById("box1");
var timer;//全局变量
btn01.onclick=function(){
//关闭上一个定时器
clearInterval(timer);
//开启定时器
timer=setInterval(function(){
//box1.offsetLeft为数值,box1.style.left为字符串
box1.style.left=box1.offsetLeft+10+"px";
//当元素移动到400px时,使其停止执行动画
//判断box1.style.left是否大于400
if(box1.offsetLeft>400){
box1.style.left=400+"px";
}
}, 30);
}
};
</script>
</head>
<body>
<button id="btn01">点击按钮以后,box1向右移动</button>
<button id="btn02">点击按钮以后,box1向左移动</button>
<br><br><br>
<div id="box1"></div>
<div style="width: 0;height: 800px;border-left: 1px black solid;position: absolute;left: 400px;"></div>
</body>
</html>