<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>定时器实现div自动</title>
<style>
body{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
border-radius: 50%;
background-color: brown;
position: absolute;
top: 0;
left: 0;
}
button{
position: absolute;
top: 100px;
left: 0;
}
input{
position: absolute;
left:100px;
top: 100px;
}
</style>
</head>
<body>
<div></div>
<button>点击开始</button>
<input type="button" value="点击停止">
<script>
// 首先获取元素的节点
var div=document.getElementsByTagName('div')[0];
var btn=document.getElementsByTagName('button')[0];
var input=document.getElementsByTagName('input')[0];
// 获取元素的宽度、高度
var divheight=div.offsetHeight;
var divwidth=div.offsetWidth;
// 获取元素距离页面顶部的距离和左侧的距离
var divtop=div.offsetTop;
var divleft=div.offsetLeft;
console.log(divtop);
// 定义偏移量
var x=10;
var y=10;
var times=null;
// 给btn添加点击事件
btn.onclick=function(){
// 点击时开启定时器
clearInterval(times);
times=setInterval(function(){
// 获取页面的内部的宽度和高度
var winwidth=document.documentElement.clientWidth;
var winheight=document.documentElement.clientHeight;
divleft += x;
divtop +=y;
// 判断如果靠近可视区域的边界着反弹
if(divtop+divheight>winheight){
divtop=winheight-divheight;
y=-y;
}
if(divleft+divwidth>winwidth){
divleft=winwidth-divwidth;
x=-x;
}
// 判断如果距离顶部为0时再反弹
if(divtop<0){
y=-y
}
if(divleft<0){
x=-x
}
div.style.top=`${divtop}`;
div.style.left=`${divleft}`;
console.log(divtop);
console.log(divleft);
},60);
}
</script>
</body>
</html>