如何避免jQuery滚动事件在同一边界区间内被反复调用
解决方案
核心逻辑是新增变量记录上一次触发功能对应的区间索引,同区间内滚动时不再重复执行对应逻辑,仅当滚动跨区间时才执行一次操作。
修改点说明
- 新增全局变量
lastActiveIndex存储上一次激活的标签索引,初始值为0,对应默认激活的第一个标签 - 点击切换标签时同步更新
lastActiveIndex,避免点击和滚动逻辑冲突 - 每次滚动事件触发时,先计算当前滚动位置对应的标签索引,仅当索引与上一次激活索引不一致时,才执行标签激活、轮播切换的逻辑,执行完成后更新存储的索引值
优化后完整JS代码
$('#navegacione li').click(function () { $('#navegacione li').removeClass('active'); $(this).addClass('active'); // 点击切换标签时同步更新记录的激活索引 lastActiveIndex = $(this).index(); }); var lastScrollLeft = 0; var anchoLi = $('#navegacione').width(); var anchoTotal = anchoLi * 4; // 新增变量记录上一次激活的标签索引,初始为0对应第一个标签 var lastActiveIndex = 0; $('#navegacione').scroll(function () { var documentScrollLeft = $('#navegacione').scrollLeft(); if (lastScrollLeft != documentScrollLeft) { lastScrollLeft = documentScrollLeft; let currentIndex = -1; // 计算当前滚动位置对应的标签索引 if(lastScrollLeft < anchoLi){ currentIndex = 0; } else if (lastScrollLeft > anchoLi - 50 && lastScrollLeft < anchoLi * 2){ currentIndex = 1; } else if(lastScrollLeft > anchoLi * 2 - 50 && lastScrollLeft < anchoLi * 3 ){ currentIndex = 2; } else if (lastScrollLeft > anchoLi * 3 -25 && lastScrollLeft < anchoLi * 4){ currentIndex = 3; } // 只有索引发生变化时才执行操作,避免同区间重复触发 if(currentIndex !== -1 && currentIndex !== lastActiveIndex){ $('#navegacione li').removeClass('active'); switch(currentIndex){ case 0: $('#descripcion').addClass('active'); // $('#carousel').carousel(0); break; case 1: $('#aprender').addClass('active'); // $('#carousel').carousel(1); break; case 2: $('#trabajar').addClass('active'); // $('#informacion-programa').carousel(2); break; case 3: $('#metodo').addClass('active'); // $('#informacion-programa').carousel(3); break; } // 更新记录的激活索引 lastActiveIndex = currentIndex; } } });
原有CSS、HTML代码无需修改可直接使用,该导航栏为移动端场景设计,测试时可使用左右方向键横向滚动导航栏验证效果。
内容的提问来源于stack exchange,提问作者Alexandro Giles
相关产品推荐
相关产品推荐

