全屏元素滚动定位卡顿求助:优化快速滚动动画体验
解决快速滚动时的卡顿问题
这个问题我太熟了!快速滚动时卡顿的根源是Waypoint被连续触发,导致多个animate动画排队执行,浏览器根本处理不过来。咱们可以通过锁定动画状态+禁用滚动干扰来解决,具体方案如下:
核心思路
- 用一个状态变量标记当前是否正在执行滚动动画,避免重复触发
- 动画执行期间,暂时禁用鼠标滚轮和触摸滚动,防止用户的操作打断动画
- 动画完成后恢复滚动功能,并重新刷新Waypoint的位置(避免因滚动动画导致的位置偏移)
修改后的代码
var $things = $('.sectionFP'); var isAnimating = false; var $htmlBody = $('html, body'); // 禁用滚动的函数 function disableScroll() { $('body').css('overflow', 'hidden'); $(window).on('wheel touchmove', function(e) { e.preventDefault(); }); } // 恢复滚动的函数 function enableScroll() { $('body').css('overflow', 'auto'); $(window).off('wheel touchmove'); } // 向下滚动的Waypoint $things.waypoint(function(direction) { if (direction === 'down' && !isAnimating) { isAnimating = true; disableScroll(); $htmlBody.animate({ scrollTop: $(this).offset().top }, 500, function() { isAnimating = false; enableScroll(); // 刷新Waypoint,确保位置准确 Waypoint.refreshAll(); }); } }, { offset: '75%' }); // 向上滚动的Waypoint $things.waypoint(function(direction) { if (direction === 'up' && !isAnimating) { isAnimating = true; disableScroll(); var laHauteurDuViewPort = $(window).height(); var laPositionDeLelement = $(this).offset().top; $htmlBody.animate({ scrollTop: laPositionDeLelement - laHauteurDuViewPort }, 500, function() { isAnimating = false; enableScroll(); Waypoint.refreshAll(); }); } }, { offset: '25%' });
代码解释
isAnimating:用来标记当前是否有滚动动画在执行,每次触发Waypoint前先检查这个状态,避免重复添加动画队列disableScroll/enableScroll:这两个函数负责在动画期间禁用页面滚动,防止用户快速滚动触发更多的Waypoint事件Waypoint.refreshAll():动画完成后刷新所有Waypoint的位置,因为滚动动画可能改变了元素的相对位置,确保后续的Waypoint触发位置准确
这样修改后,不管用户怎么快速滚动,都会等待当前的定位动画完成后,才允许继续操作,彻底解决卡顿问题。
内容的提问来源于stack exchange,提问作者user3951700
相关产品推荐
相关产品推荐

