JavaScript实现滚动缩放中间图片功能:无法缩小并固定上方图片位置
修复方案
核心问题
- 中间图片
sticky定位未指定top: 0属性,无法实现滚动到视口顶部后固定的效果 - 原有逻辑采用硬编码阈值判断触发条件,无法匹配不同设备、不同滚动距离的场景
- 滚轮事件的delta计算逻辑与滚动补偿逻辑冲突,导致图片缩小功能失效
- 全局阻止滚轮默认行为,会导致页面其他区域无法正常滚动
修正后代码
HTML
<div style="height: 1000px">some HTML</div> <div class="flex-container"> <img src="替换为你的上方图片地址" id="scroll-sup" class="scroll-img" /> <img src="替换为你的中间图片地址" id="scroll-int" class="scroll-img" style="position: sticky; top: 0; object-fit: fill; height: 0;" /> <img src="替换为你的下方图片地址" id="scroll-inf" class="scroll-img" /> </div> <div style="height: 1000px">some more HTML</div>
CSS
.flex-container { display: flex; flex-direction: column; align-items: flex-start; } .scroll-img { border-radius: 0px; width: 100%; flex-shrink: 0; }
JavaScript
const upperImg = document.getElementById("scroll-sup"); const middleImg = document.getElementById("scroll-int"); const lowerImg = document.getElementById("scroll-inf"); const minHeight = 0; const maxHeight = document.documentElement.clientHeight - 50; // 预计算元素基准尺寸 const upperHeight = upperImg.offsetHeight; const lowerHeight = lowerImg.offsetHeight; const containerTop = upperImg.parentElement.offsetTop; window.addEventListener('scroll', () => { const scrollY = window.scrollY; const upperRect = upperImg.getBoundingClientRect(); const lowerRect = lowerImg.getBoundingClientRect(); // 阶段1:下方图片未完全进入可视区,中间图高度为0 if (lowerRect.top > window.innerHeight) { middleImg.style.height = `${minHeight}px`; return; } // 阶段2:上方图片还没到顶部,中间图逐步放大,保持下方图在底部 if (upperRect.top > 0) { const calcHeight = window.innerHeight - lowerRect.top - lowerHeight; middleImg.style.height = `${Math.min(Math.max(calcHeight, minHeight), maxHeight)}px`; return; } // 阶段3:上方图片已固定在顶部,中间图逐步缩小 const offset = scrollY - (containerTop + upperHeight); const calcHeight = maxHeight - offset; middleImg.style.height = `${Math.min(Math.max(calcHeight, minHeight), maxHeight)}px`; });
内容的提问来源于stack exchange,提问作者a96lex
相关产品推荐
相关产品推荐

