利用JS实现自由落体
理解重点:每次降落到底部判断一次speed是否为0如果是则结束
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</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>
<script>
var oCont = document.querySelector('.cont');
var oBox = document.querySelector('.box');
console.log(oCont.offsetHeight);
var h = oCont.offsetHeight - oBox.offsetHeight;
var speed = 10;
var g = 2;
var times = '';
document.onclick = function () {
clearInterval(times);
times = setInterval(() => {
speed += g;
if (speed >= h - oBox.offsetTop) {
oBox.style.top = h + 'px';
speed = -parseInt(speed * 0.8);
if (Math.abs(speed) < 1) {
clearInterval(times);
}
} else {
console.log(oBox.offsetTop);
console.log(speed);
oBox.style.top = oBox.offsetTop + speed + 'px';
}
}, 30);
}
</script>
</body>
</html>