使用jQuery实现滚动时div淡出后无法保持隐藏的问题求助
问题分析与修复方案
你的代码出现“淡出后立刻重新淡入”的问题,核心原因有两个:
- scroll事件触发太频繁:滚动过程中这个事件会被连续触发几十次,每次都调用
fadeOut()或fadeIn(),jQuery会把这些动画放进队列,导致前一个动画还没做完,下一个就打断它,出现反复切换的情况。 - 没有判断元素状态:比如元素已经隐藏时,你还在调用
fadeOut(),元素已经显示时还在调用fadeIn(),重复触发动画会加剧队列混乱。
修复后的代码
$(window).on("load", function() { $(window).scroll(function() { const scrollTop = $(this).scrollTop(); const $intro = $("#intro"); if (scrollTop > 20) { // 只有元素可见时才执行淡出,先停止当前动画避免队列堆积 if ($intro.is(":visible")) { $intro.stop(true, true).fadeOut(); } } else { // 只有元素隐藏时才执行淡入 if ($intro.is(":hidden")) { $intro.stop(true, true).fadeIn(); } } }); });
关键修改说明
- 状态判断:用
is(":visible")和is(":hidden")检查元素当前状态,避免重复执行相同状态的动画。 stop(true, true):第一个true清空所有待执行的动画队列,第二个true让当前动画直接跳到结束状态,彻底解决动画冲突的问题。- 缓存DOM元素:把
$("#intro")存进变量,不用每次滚动都重新查找DOM,提升性能。
如果想进一步优化性能(减少scroll事件的执行次数),可以加个防抖函数,让滚动停止后再执行逻辑:
$(window).on("load", function() { // 防抖函数:指定时间内只执行最后一次触发 function debounce(func, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(func, delay); }; } const scrollHandler = debounce(function() { const scrollTop = $(window).scrollTop(); const $intro = $("#intro"); if (scrollTop > 20) { $intro.is(":visible") && $intro.stop(true, true).fadeOut(); } else { $intro.is(":hidden") && $intro.stop(true, true).fadeIn(); } }, 50); // 50ms内的滚动只执行一次 $(window).scroll(scrollHandler); });
内容的提问来源于stack exchange,提问作者tom
相关产品推荐
相关产品推荐

