<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.cont {
width: 1000px;
height: 600px;
background: #eee;
margin: 20px auto;
position: relative;
}
.box {
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="cont">
<div class="box"></div>
</div>
</body>
<script type="text/javascript">
// 1 获取节点
let contObj = document.querySelector('.cont');
let boxObj = document.querySelector('.box');
// 2 设置变量
let speed = 10;
let g = 2;
let times = '';
// 小球的最大目标值
let target = contObj.offsetHeight - boxObj.offsetHeight;
// 3 页面点击之后小球下落
document.onclick = () => {
// 设置定时器
times = setInterval(function () {
// 3-1 给步进值添加重力
speed += g;
console.log(speed, '+');
// 3-2 到达目标,停止运动
if (boxObj.offsetTop + speed > target) {
//
// 3-3 强制设置到目标
boxObj.style.top = target + 'px'
// 3-4 设置speed为负
speed = -(speed * 0.8);
// console.log(speed, '-');
// 3-5 判断speed小于1,则停止定时器
if (Math.abs(speed) < 1) clearInterval(times);
} else {
boxObj.style.top = boxObj.offsetTop + speed + 'px';
}
}, 30)
}
</script>
</html>