<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Banner 弹出小球动画</title>
<style>
.banner {
position: relative;
width: 100%;
height: 100vh;
background: url('banner-bg.jpg') no-repeat center center;
background-size: cover;
overflow: hidden;
}
.ball {
position: absolute;
bottom: -50px;
left: 50%;
transform: translateX(-50%);
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
transition: 1s ease-in-out;
}
</style>
</head>
<body>
<div class="banner">
<div class="ball"></div>
</div>
<script>
window.addEventListener('scroll', function() {
var banner = document.querySelector('.banner');
var ball = document.querySelector('.ball');
var bannerTop = banner.getBoundingClientRect().top;
var scrollPercent = 100 - (Math.abs(bannerTop) / (window.innerHeight - banner.offsetHeight) * 100);
if (scrollPercent >= 0 && scrollPercent <= 100) {
ball.style.transform = 'translateY(' + (scrollPercent - 100) * 1.5 + 'px) translateX(-50%)';
}
});
</script>
</body>
</html>
这段代码实现了滚动时小球上移的效果,并且根据滚动位置计算小球的移动距离。当用户滚动到 Banner 区域时,小球会根据滚动的进度上移,创造出滚动触发的动画效果。