网页模板飞入效果,HTML上下左右飞入效果代码
:本站 2025-10-27 21:01:32 :28

css
/* 基础动画类:所有动画元素共享的公共样式 */
.animate-element {
opacity: 0; /* 初始状态不可见 */
/* 建议添加以下属性以优化动画性能 */
will-change: transform, opacity;
}
/* 定义关键帧动画:从左向右飞入 */
@keyframes flyInLeft {
from {
opacity: 0;
transform: translateX(-100px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
/* 定义关键帧动画:从右向左飞入 */
@keyframes flyInRight {
from {
opacity: 0;
transform: translateX(100px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
/* 定义关键帧动画:从下向上飞入 (你想要的效果) */
@keyframes flyInUp {
from {
opacity: 0;
transform: translateY(50px); /* 调整起始位置 */
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 定义关键帧动画:从上向下飞入 */
@keyframes flyInDown {
from {
opacity: 0;
transform: translateY(-50px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 缩放淡入效果 (作为扩展示例) */
@keyframes zoomIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* 动画效果类:将这些类附加到元素上以触发特定动画 [3](@ref) */
.animate-element.in-view.animate--left { animation: flyInLeft 0.6s ease-out forwards; }
.animate-element.in-view.animate--right { animation: flyInRight 0.6s ease-out forwards; }
.animate-element.in-view.animate--up { animation: flyInUp 0.6s ease-out forwards; }
.animate-element.in-view.animate--down { animation: flyInDown 0.6s ease-out forwards; }
.animate-element.in-view.animate--zoom { animation: zoomIn 0.6s ease-out forwards; }
/* 可选:为不同的元素设置不同的动画延迟,实现错峰序列效果 */
/* 延迟类只定义延迟时间,且确保在 in-view 状态下才生效 */
.animate-element.in-view.delay-1 { animation-delay: 0.1s; }
.animate-element.in-view.delay-2 { animation-delay: 0.5s; }
.animate-element.in-view.delay-3 { animation-delay: 1s; }
.animate-element.in-view.delay-4 { animation-delay: 1.3s; }JS
<script>
document.addEventListener('DOMContentLoaded', function() {
c***t animatedElements = document.querySelectorAll('.animate-element');
if ('IntersectionObserver' in window) {
// 创建观察器,配置参数是关键
c***t observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 使用 requestAnimationFrame 确保流畅触发
requestAnimationFrame(() => {
entry.target.classList.add('in-view');
// 可选:动画触发后停止观察,避免重复触发
// observer.unobserve(entry.target);
});
} else {
// 通常不需要在离开视口时移除类,除非你想做反向动画
// entry.target.classList.remove('in-view');
}
});
}, {
threshold: 0.1, // 当元素有10%进入视口时就触发,不易错过
rootMargin: '0px 0px -50px 0px' // 底部负边距,实现"提前"触发
});
// 开始观察每一个元素
animatedElements.forEach(el => {
observer.observe(el);
});
} else {
// 降级方案:如果不支持,可以直接显示所有元素
animatedElements.forEach(el => {
el.classList.add('in-view');
});
}
});
</script>html
<div class="d-flex align-items-center my-3 animate-element delay-1">
<!-- 第一个元素的内容 -->
</div>
<div class="d-flex align-items-center my-3 animate-element delay-2">
<!-- 第二个元素的内容 -->
</div>
<div class="d-flex align-items-center my-3 animate-element delay-3">
<!-- 第三个元素的内容 -->
</div>
本文编辑:admin
:




















