效果图

代码
html
<div class="ball">🏀</div>
<button class="go">go</button>
css
:root {
--top: 0px;
}
.ball {
position: absolute;
top: var(--top);
font-size: 100px;
}
.go {
position: fixed;
right: 80px;
top: 50px;
}
javascript
let prev = 0;
const duration = 3000;
const height = 500;
function bounce(t) {
if (!prev) {
prev = t;
requestAnimationFrame(bounce);
return;
}
let diff = t - prev;
let x = diff / duration;
let y = easeOutBounce(x);
let top = y * height;
document.documentElement.style.setProperty('--top', top + 'px');
if (diff >= duration) {
return;
}
requestAnimationFrame(bounce);
}
let go = document.querySelector(".go")
go.addEventListener('click', (e) => {
prev = 0;
requestAnimationFrame(bounce);
})
function easeOutBounce(x) {
const n1 = 7.5625;
const d1 = 2.75;
if (x < 1 / d1) {
return n1 * x * x;
} else if (x < 2 / d1) {
return n1 * (x -= 1.5 / d1) * x + 0.75;
} else if (x < 2.5 / d1) {
return n1 * (x -= 2.25 / d1) * x + 0.9375;
} else {
return n1 * (x -= 2.625 / d1) * x + 0.984375;
}
}
在线演示
jsbin.com/labidan/edi…