Smooth Scroll 在 Safari 上为什么不生效?

熙然~ 阅读 52

我在项目里用了 scroll-behavior: smooth; 实现页面锚点平滑滚动,Chrome 和 Firefox 都没问题,但在 Safari 上完全没效果,还是瞬间跳转。

查了下资料说 Safari 支持需要加前缀?但我试了 -webkit-scroll-behavior: smooth; 也没用。是不是还有别的写法或者需要 JS 回退方案?

html {
  scroll-behavior: smooth;
}
我来解答 赞 20 收藏
二维码
手机扫码查看
2 条解答
Tr° 议谣
Safari确实对原生的 scroll-behavior: smooth; 支持不太好,直到最近几个版本才有部分支持,但还是不太稳定。这里有个靠谱的JS回退方案:

function smoothScrollTo(target) {
const targetElement = document.querySelector(target);
if (!targetElement) return;

const targetPosition = targetElement.getBoundingClientRect().top + window.scrollY;
let startPosition = window.scrollY;
const distance = targetPosition - startPosition;

let startTime = null;

function animation(currentTime) {
if (startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = ease(timeElapsed, startPosition, distance, 1000);
window.scrollTo(0, run);
if (timeElapsed < 1000) requestAnimationFrame(animation);
}

function ease(t, b, c, d) {
t /= d / 2;
if (t < 1) return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}

requestAnimationFrame(animation);
}

// 使用示例
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
smoothScrollTo(this.getAttribute('href'));
});
});


这个方案用 requestAnimationFrame 来实现动画效果,兼容性更好。顺便说下,这种问题处理起来挺烦人的,不同浏览器总是有各种小差异,不过用JS回退算是比较稳妥的办法了。
点赞
2026-03-26 16:10
紫萱
紫萱 Lv1
应该是 Safari 对 scroll-behavior 的支持还不完整(尤其旧版本),而且加 -webkit- 前缀确实没用——这属性目前还不支持前缀。
先确认 Safari 版本(14+ 才支持),如果还要兼容旧版,直接上 JS 回退方案:
document.documentElement.style.scrollBehavior = 'smooth'

或者用 scrollIntoView({ behavior: 'smooth' }) 替代锚点跳转,实测 Safari 全兼容。
点赞 4
2026-02-23 18:13