js实现开屏动画
实现开屏动画的方法
使用JavaScript实现开屏动画可以通过多种方式完成,以下是几种常见的方法:
使用CSS动画结合JavaScript控制
通过CSS定义动画效果,JavaScript控制动画的播放和结束时机。
<style>
.splash-screen {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
animation: fadeOut 1s ease-in-out 2s forwards;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; visibility: hidden; }
}
</style>
<div class="splash-screen">
<h1>欢迎来到我的网站</h1>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
setTimeout(() => {
const splash = document.querySelector('.splash-screen');
splash.style.animation = 'fadeOut 1s ease-in-out forwards';
}, 2000);
});
</script>
纯JavaScript动画实现
使用requestAnimationFrame实现更复杂的动画效果。
<div id="splash" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #000; color: white; display: flex; justify-content: center; align-items: center;">
<h1>加载中...</h1>
</div>
<script>
let opacity = 1;
const splash = document.getElementById('splash');
function animate() {
opacity -= 0.01;
splash.style.opacity = opacity;
if (opacity > 0) {
requestAnimationFrame(animate);
} else {
splash.style.display = 'none';
}
}
setTimeout(() => {
requestAnimationFrame(animate);
}, 2000);
</script>
使用GSAP动画库
GSAP提供了强大的动画控制能力,适合复杂的开屏动画需求。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
<div id="splash" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(45deg, #ff00cc, #3333ff); color: white; display: flex; justify-content: center; align-items: center; z-index: 9999;">
<h1>欢迎光临</h1>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
gsap.to("#splash", {
opacity: 0,
duration: 1,
delay: 2,
onComplete: () => {
document.getElementById("splash").style.display = "none";
}
});
});
</script>
关键注意事项
- 确保开屏动画在所有资源加载完成后才开始播放,可以使用
DOMContentLoaded事件 - 考虑移动设备和桌面设备的不同表现,可能需要添加响应式设计
- 动画结束后应移除或隐藏开屏元素,避免影响页面交互
- 对于复杂动画,考虑使用专门的动画库如GSAP、Anime.js等
- 测试动画在不同浏览器中的表现,确保兼容性
进阶技巧
对于更专业的开屏动画,可以结合以下技术:

- 使用Canvas或WebGL实现高性能粒子动画
- 添加进度条显示实际加载进度
- 实现品牌logo的特殊动画效果
- 考虑添加跳过按钮,让用户可以提前结束动画
- 使用localStorage记录用户是否已经看过开屏动画,避免重复显示






