You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求实现类似示例的CSS/JS上滑淡入滚动动画(附项目链接)

解决滚动触发图片上移淡入动画的方案

Hey there! First off, huge props to you for building out the HTML/CSS foundation and tackling this cool scroll animation at 13—seriously, that’s awesome! Let’s get that animation working step by step:

1. 给图片设置初始CSS状态

首先,我们要让需要动画的图片处于"待激活"的初始状态:透明、向下偏移一段距离,这样滚动时的上移和淡入效果才会明显:

/* 替换成你项目里实际的图片容器类名 */
.image-container {
  opacity: 0;
  transform: translateY(30px); /* 初始位置向下偏移30px */
  transition: all 0.6s ease-out; /* 0.6秒的平缓过渡动画 */
}

2. 编写触发动画的CSS类

接下来,我们定义一个类,用来控制图片完成动画后的最终状态:

.image-container.animate {
  opacity: 1;
  transform: translateY(0); /* 回到原始位置 */
}

3. 用JS监听滚动,判断元素是否进入视口

我们用Intersection Observer API(现代浏览器支持的高效监听方式,比传统滚动事件性能更好)来检测图片进入视口时,给它加上上面的animate类:

// 选中所有需要动画的图片容器
const imageContainers = document.querySelectorAll('.image-container');

// 创建观察者实例
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    // 当元素进入视口时
    if (entry.isIntersecting) {
      entry.target.classList.add('animate');
      // 可选:如果只想触发一次动画,加上这行停止监听该元素
      observer.unobserve(entry.target);
    }
  });
}, {
  // 调整这个值可以改变触发时机,0.1表示元素10%进入视口就触发
  threshold: 0.1
});

// 给每个图片容器添加监听
imageContainers.forEach(container => {
  observer.observe(container);
});

兼容旧浏览器的备选方案(可选)

如果需要支持不兼容Intersection Observer的旧浏览器,可以用传统的滚动事件监听(性能稍差,但可用):

function checkScrollPosition() {
  imageContainers.forEach(container => {
    const containerTop = container.getBoundingClientRect().top;
    const windowHeight = window.innerHeight;
    
    // 当容器进入视口90%位置时触发动画
    if (containerTop < windowHeight * 0.9) {
      container.classList.add('animate');
    }
  });
}

// 页面加载时先检查一次,滚动时再实时检查
window.addEventListener('load', checkScrollPosition);
window.addEventListener('scroll', checkScrollPosition);

4. 根据你的项目调整细节

  • 可以修改translateY(30px)来改变图片上移的距离,调整0.6s来控制动画时长,或者把ease-out换成ease-in-out这类不同的过渡曲线。
  • 确认你的图片容器没有冲突的CSS样式(比如overflow: hidden或奇怪的定位),避免影响动画效果。

小提示:可以按F12打开浏览器开发者工具,检查元素是否在滚动时正确添加了animate类,方便调试问题哦!

内容的提问来源于stack exchange,提问作者Hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:14:25