能否通过CSS为scroll-behavior: smooth自定义缓动函数?
仅靠CSS无法自定义JS触发的scrollTop平滑滚动缓动效果
你当前的场景里,只用CSS做不到自定义缓动效果。原因很直接:CSS的scroll-behavior: smooth只能触发浏览器原生的平滑滚动,而目前没有任何CSS属性可以修改这个原生滚动的缓动曲线——不管是cubic-bezier(0.42, 0, 0.58, 1)还是ease-out这类值,都没法直接作用在原生的scroll-behavior平滑滚动上。
要实现自定义缓动的平滑滚动,得用JavaScript手动模拟这个过程,放弃依赖原生的scroll-behavior。下面是修改后的示例代码,用requestAnimationFrame结合自定义缓动函数来实现:
修改后的完整代码
HTML(与原代码一致)
<div id="container"> <div>row 1</div> <div>row 2</div> <div>row 3</div> <div>row 4</div> <div>row 5</div> <div>row 6</div> <div>row 7</div> <div>row 8</div> <div>row 9</div> <div>row 10</div> </div> <button id="scroll">Scroll</button>
CSS(移除原生平滑滚动配置)
#container { min-height: 100px; max-height: 100px; display: flex; flex-direction: column; overflow-y: auto; border: 1px solid black; margin-bottom: 10px; /* 去掉原生平滑滚动,改用JS实现自定义效果 */ /* scroll-behavior: smooth; */ } #container > div:nth-child(odd){ background: #efefef; }
JavaScript(实现自定义缓动的平滑滚动)
// 自定义缓动函数:对应你要的cubic-bezier(0.42, 0, 0.58, 1) function cubicBezierEase(t) { return t * t * (3 - 2 * t); } // 通用平滑滚动函数 function smoothScrollTo(element, targetY, duration = 500) { const startY = element.scrollTop; const distance = targetY - startY; let startTime = null; function animation(currentTime) { if (!startTime) startTime = currentTime; const timeElapsed = currentTime - startTime; const progress = Math.min(timeElapsed / duration, 1); const easedProgress = cubicBezierEase(progress); element.scrollTop = startY + distance * easedProgress; if (timeElapsed < duration) { requestAnimationFrame(animation); } } requestAnimationFrame(animation); } // 绑定按钮点击事件 document.getElementById("scroll").addEventListener("click", function() { const container = document.getElementById("container"); if (container.scrollTop === 0) { smoothScrollTo(container, 100); } else { smoothScrollTo(container, 0); } });
额外说明
- 如果你需要
ease-out效果,只需要替换缓动函数即可:function easeOut(t) { return 1 - Math.pow(1 - t, 3); } - 调整
smoothScrollTo函数的duration参数(单位:毫秒),可以控制滚动的快慢。
内容的提问来源于stack exchange,提问作者Ben Holness
相关产品推荐
相关产品推荐

