Angular开启scrollPositionRestoration后如何禁用平滑滚动?
Angular路由滚动恢复禁用平滑滚动方案
问题说明
Angular开启scrollPositionRestoration: 'enabled'实现路由滚动位置自动恢复时,默认会触发平滑滚动效果,不符合常规网站前进后退的交互体验。
解决方案
方案1:配置scrollBehavior参数(适用于Angular v14+)
直接在RouterModule.forRoot配置中新增scrollBehavior配置项,指定滚动行为为无过渡的直接跳转即可,修改后的代码如下:
@NgModule({ imports: [ RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled', // 新增以下配置,禁用平滑滚动 scrollBehavior: (position) => position ? {...position, behavior: 'auto'} : {top: 0, left: 0, behavior: 'auto'} }), ], exports: [RouterModule] }) export class AppRoutingModule { }
方案2:自定义滚动恢复逻辑(适用于所有Angular版本)
如果使用的Angular版本低于v14,可以关闭默认的滚动恢复能力,自行监听路由事件实现滚动逻辑:
- 首先修改路由配置,关闭默认滚动恢复:
@NgModule({ imports: [ RouterModule.forRoot(routes, { scrollPositionRestoration: 'disabled' }), ], exports: [RouterModule] }) export class AppRoutingModule { }
- 在根组件
AppComponent中监听路由滚动事件,自定义滚动逻辑:
import { Component, OnInit } from '@angular/core'; import { Router, Scroll } from '@angular/router'; import { filter } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { constructor(private router: Router) {} ngOnInit() { this.router.events.pipe( filter(event => event instanceof Scroll) ).subscribe((scrollEvent: Scroll) => { // 前进/后退场景,恢复历史滚动位置 if (scrollEvent.position) { window.scrollTo({ top: scrollEvent.position[0], left: scrollEvent.position[1], behavior: 'auto' }); return; } // 锚点跳转场景(按需保留) if (scrollEvent.anchor) { document.getElementById(scrollEvent.anchor)?.scrollIntoView({ behavior: 'auto' }); return; } // 新页面跳转场景,默认滚动到顶部 window.scrollTo({ top: 0, left: 0, behavior: 'auto' }); }); } }
注意事项
先检查全局样式文件中是否存在html { scroll-behavior: smooth; }的配置,如果有需要修改为scroll-behavior: auto;,避免全局样式覆盖路由的滚动行为配置。
内容的提问来源于stack exchange,提问作者Mick
相关产品推荐
相关产品推荐

