单页网站导航栏当前区块高亮及无jQuery平滑滚动速度优化问题
问题原因
- 你当前点击事件绑定的
smooth滚动逻辑,每帧仅滚动1像素,按常规60帧/秒的刷新率计算,滚动1000像素的距离就需要近17秒,是速度过慢的核心原因。 - 代码中实现的
smoothScroll方法本身是固定时长的滚动逻辑,但你没有将它绑定到点击事件,并未实际生效。
优化方案(完全不依赖jQuery)
方案1:使用原生API实现(推荐)
现代浏览器原生支持scrollTo方法的平滑滚动配置,无需自己实现复杂的滚动逻辑,性能和流畅度都更优,直接替换点击事件的绑定逻辑即可:
// 替换原events方法里的anchorLinks点击监听代码 SS.forEach(SS.el.anchorLinks, function (index, link) { link.addEventListener('click', function(e) { e.preventDefault(); const target = document.querySelector(this.getAttribute('href')); window.scrollTo({ top: target.offsetTop, behavior: 'smooth' }); }); });
如果需要调整滚动速度,只需要给html标签添加CSS的scroll-behavior属性配合自定义滚动规则即可:
html { scroll-behavior: smooth; }
方案2:自定义滚动逻辑(兼容旧浏览器)
如果需要兼容不支持原生平滑滚动的旧浏览器,可以修改原smooth方法,通过固定滚动总时长的方式控制速度,避免按像素步进的问题:
smooth: function (e) { e.preventDefault(); const id = e.currentTarget.getAttribute('href'); const targetNode = document.querySelector(id); const startScrollY = window.scrollY; const targetScrollY = targetNode.offsetTop; const scrollDistance = targetScrollY - startScrollY; const scrollDuration = 350; // 滚动总时长,单位ms,数值越小滚动速度越快 let startTime = null; const scrollAnimation = function(timestamp) { if (!startTime) startTime = timestamp; const runTime = timestamp - startTime; // 计算滚动进度,最大为1 const progress = Math.min(runTime / scrollDuration, 1); // 可替换为缓动公式实现更自然的滚动效果,比如easeInOut window.scrollTo(0, startScrollY + scrollDistance * progress); if (runTime < scrollDuration) { window.requestAnimationFrame(scrollAnimation); } }; window.requestAnimationFrame(scrollAnimation); }
你可以根据自己的需求调整scrollDuration的数值,300-500ms是大部分网站通用的交互区间。
内容的提问来源于stack exchange,提问作者Casper Poulsen
相关产品推荐
相关产品推荐

