GitHub上有一个插件可以解决这个问题:
全局安装
npm install smoothscroll-polyfill --save
使用
// 引入
import smoothscroll from 'smoothscroll-polyfill'
// 如果浏览器不支持scroll behavior(比如Safari就不支持),就执行
if (!('scrollBehavior' in document.documentElement.style)) {
smoothscroll.polyfill()
}
// 执行带有behavior的滚动
window.scrollTo({
top:xxx,
behavior:'smooth',
})
原理
想要了解这个插件原理的,直接去GitHub上翻源码看看: