滚动切换子元素:当前子元素淡出,下一个子元素显示实现求助
解决滚动时子元素淡入淡出切换的问题
先聊聊你原代码里的几个核心问题:
- 首先,
.parent默认没有固定高度和滚动属性,所以$('.parent').scroll()事件根本不会触发。如果是监听页面滚动,应该用$(window).scroll();如果要父容器内部滚动,得给.parent设置height和overflow: auto。 - 其次,
$(this).next().children().show()逻辑错了——$(this)是.parent,它的next()是兄弟元素,不是子元素的下一个,得针对当前显示的子元素去获取下一个兄弟。 - 另外,所有
.children都设position: sticky; top:0会导致它们全部堆叠在顶部,没法自然切换,得调整每个子元素的高度,让它们占满父容器(或视口),这样滚动时才会触发切换时机。
下面是修正后的完整实现方案:
第一步:调整HTML和基础样式
给父容器设置合适的高度,子元素占满父容器高度,保证滚动时能逐个切换:
<div class="parent"> <div class="children">1</div> <div class="children">2</div> <div class="children">3</div> <div class="children">4</div> </div>
.parent { height: 100vh; /* 占满整个视口高度,适配页面滚动场景 */ overflow-y: auto; /* 允许父容器内部滚动 */ } .children { height: 100vh; /* 每个子元素占满父容器高度 */ display: flex; align-items: center; justify-content: center; font-size: 3rem; position: relative; /* 替换sticky,避免元素堆叠 */ }
第二步:修正jQuery逻辑
我们用一个变量跟踪当前显示的子元素索引,避免重复触发动画,同时通过滚动位置计算切换时机:
$(document).ready(function() { let currentIndex = 0; const $children = $('.children'); const totalChildren = $children.length; const childHeight = $children.eq(0).outerHeight(); // 初始化:只显示第一个子元素,其余隐藏 $children.hide().eq(currentIndex).show(); $('.parent').scroll(function() { const scrollTop = $(this).scrollTop(); // 计算当前滚动到哪个子元素的位置 const newIndex = Math.floor(scrollTop / childHeight); // 只有索引变化且在有效范围内时,才触发淡入淡出 if (newIndex !== currentIndex && newIndex < totalChildren) { $children.eq(currentIndex).fadeOut(500); $children.eq(newIndex).fadeIn(500); currentIndex = newIndex; } }); });
如果需要监听页面全局滚动(而非父容器内部滚动),只需把监听对象改成$(window),并调整滚动位置计算:
$(document).ready(function() { let currentIndex = 0; const $children = $('.children'); const totalChildren = $children.length; const childHeight = $(window).height(); $children.hide().eq(currentIndex).show(); $(window).scroll(function() { const scrollTop = $(this).scrollTop(); const newIndex = Math.floor(scrollTop / childHeight); if (newIndex !== currentIndex && newIndex < totalChildren) { $children.eq(currentIndex).fadeOut(500); $children.eq(newIndex).fadeIn(500); currentIndex = newIndex; } }); });
这样就能实现滚动时,当前子元素平滑淡出,下一个子元素自然进入视野的效果了。
内容的提问来源于stack exchange,提问作者Ramesh
相关产品推荐
相关产品推荐

