幾天前進行了一場前端實習面試,題目是用面向對象的方法實現點擊後小球自由落體彈跳運動,覺得很有意思,現在有空整理一下。
一些簡單的CSS樣式和基礎的HTML
#bg{
top:0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
}
.ball{
position: absolute;
border-radius: 50%;
width:50px;
height:50px;
background: radial-gradient(circle at 50px 50px, #ffd3d1, #b01700);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ball</title>
<link rel="stylesheet" href="ball.css">
</head>
<body>
<div id="bg"></div>
</body>
<script src="ball.js"></script>
<script>
// 點擊事件我寫在此處
</script>
</html>
好了,現在開始工作。
- 首先,我們需要一個Ball類的構造函數
constructor(left, top, ballID) {
this.ballID = ballID; //小球的ID,爲唯一標識符
this.x = left; //小球的橫座標
this.y = top; //小球的縱座標
this.g = 9.8; //重力加速度
this.v = 0; //小球的速度
this.isStop = false; //判斷當前運動是否應該停止
this.createBall(); //創建小球的DOM
let intervalSetting = window.setInterval(()=>{ //這裏使用箭頭函數,函數的this指針問題需要注意一下。
this.move();
if (this.isStop) {
clearInterval(intervalSetting);
}
}, 1);
}
- 創建該小球的DOM,設置其位置,添加ball類以讓後面添加的小球獲取ID
createBall() {
let ballDiv = document.createElement('div');
ballDiv.setAttribute('id', this.ballID);
document.getElementById('bg').appendChild(ballDiv);
let ballDom = document.getElementById(this.ballID);
ballDom.classList.add('ball');
ballDom.style.top = this.y + 'px';
ballDom.style.left = this.x + 'px';
}
- 然後是小球的移動
move() {
// 0.001秒是setInterval的時間間隔,我將其看作是0.001秒內的勻速運動
if (this.y >= window.innerHeight - 50 && this.v > 0) { // 如果小球下降過程中接觸到屏幕底部。小球的直徑爲50px
this.rebound(); //小球反彈
} else { //自由落體
this.v = this.v + this.g * 4000 * 0.001; // 公式:v = v0 + gt, 1 m = 3779.527559 px,這裏約等於4000
}
this.y = this.y + this.v * 0.001; // 公式:s = s + vt
document.getElementById(this.ballID).style.top = this.y + 'px';
}
- 最後,點擊事件和創建對象
document.getElementById('bg').onclick = function (e) {
let ballID = document.querySelectorAll('.ball').length + 1;
let ballObj = new Ball(e.clientX, e.clientY, ballID);
};
實現效果: