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

如何实现滚动时div内图片折叠,仅保留项目标题?

实现滚动时项目容器折叠效果

核心思路

监听页面滚动事件,当容器进入视口后固定其位置,随滚动距离逐步缩小容器高度,隐藏图片区域,直到仅保留标题高度;完成折叠后,容器恢复随页面滚动。


步骤1:HTML结构调整

在.projectscontainer外层添加占位容器,避免固定容器时页面布局跳动:

<div class="container-placeholder">
  <div class="projectscontainer">
    <!-- 你的项目内容:图片、标题等 -->
  </div>
</div>

步骤2:CSS样式修改

  1. 给占位容器设置初始高度,匹配容器展开时的尺寸:
.container-placeholder {
  height: 498px; /* 和.projectscontainer初始高度一致 */
}
  1. 调整.projectscontainer及内部元素样式,实现内容隐藏逻辑:
.projectscontainer {
  border: solid 2px #593832;
  width: 988px;
  height: 498px;
  overflow: hidden; /* 超出容器的内容隐藏 */
  position: relative; /* 内部绝对定位元素的参考 */
  margin: 0 auto; /* 保持居中,可根据你的布局调整 */
}

/* 项目标题固定在容器底部 */
.projecttitle {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 91px; /* 固定标题高度 */
  /* 保留你原有的标题样式(背景、文字排版等) */
}

/* 项目图片区域占容器除标题外的高度 */
.projectimage {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: calc(100% - 91px); /* 自动适配容器剩余高度 */
  object-fit: cover; /* 保持图片比例,避免拉伸 */
}

步骤3:JavaScript实现滚动逻辑

添加以下脚本,处理滚动时的容器状态切换:

// 获取元素
const container = document.querySelector('.projectscontainer');
const placeholder = document.querySelector('.container-placeholder');

// 配置参数
const initialHeight = 498; // 容器初始高度
const targetHeight = 91; // 折叠后的目标高度
const heightDiff = initialHeight - targetHeight; // 需要收缩的总高度
const containerTop = container.offsetTop; // 容器初始距离页面顶部的位置

// 监听滚动事件
window.addEventListener('scroll', () => {
  const scrollY = window.scrollY;

  // 情况1:滚动到容器顶部,开始折叠
  if (scrollY >= containerTop && scrollY < containerTop + heightDiff) {
    const currentHeight = initialHeight - (scrollY - containerTop);
    container.style.height = `${currentHeight}px`;
    container.style.position = 'fixed';
    container.style.top = '0';
    placeholder.style.height = `${initialHeight}px`;
  }
  // 情况2:折叠完成,容器随页面滚动
  else if (scrollY >= containerTop + heightDiff) {
    container.style.height = `${targetHeight}px`;
    container.style.position = 'relative';
    container.style.top = `${heightDiff}px`;
    placeholder.style.height = `${targetHeight}px`;
  }
  // 情况3:未滚动到容器,恢复初始状态
  else {
    container.style.height = `${initialHeight}px`;
    container.style.position = 'static';
    container.style.top = '0';
    placeholder.style.height = `${initialHeight}px`;
  }
});

关键细节说明

  • overflow:hidden:容器高度缩小时,超出的图片区域会被自动隐藏,实现“上滑消失”的视觉效果。
  • 占位容器:解决position:fixed导致容器脱离文档流的布局跳动问题,保持页面滚动流畅。
  • 滚动区间判断:精准控制容器在「未进入视口→折叠中→折叠完成」三个状态间的切换逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:13:16