You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ngx-page-scroll时如何实现滚动自动切换激活链接?

实现步骤

1. 确认模块导入

首先确保你在对应模块中已经导入了ngx-page-scroll的依赖模块:

import { NgxPageScrollCoreModule } from 'ngx-page-scroll-core';
import { NgxPageScrollModule } from 'ngx-page-scroll';

@NgModule({
  imports: [
    // 可根据需要配置全局参数,比如滚动动画时长、滚动偏移量
    NgxPageScrollCoreModule.forRoot({duration: 600, scrollOffset: 70}),
    NgxPageScrollModule
  ]
})
export class AppModule { }

2. 调整模板代码

ngx-page-scroll自带了pageScrollSpy相关指令,专门用来实现滚动时锚点对应激活的效果,修改后的代码如下:

<nav class="navbar">
  <ul class="navbar-items">
    <!-- 给每个导航链接添加pageScrollSpy指令,绑定激活类 -->
    <li>
      <a 
        pageScroll 
        pageScrollSpy="default" 
        href="#default" 
        [class.active]="pageScrollSpyService.currentSpyItem === 'default'"
      >
        Default
      </a>
    </li>
    <li>
      <a 
        pageScroll 
        pageScrollSpy="first" 
        href="#first" 
        [class.active]="pageScrollSpyService.currentSpyItem === 'first'"
      >
        First
      </a>
    </li>
    <li>
      <a 
        pageScroll 
        pageScrollSpy="second" 
        href="#second" 
        [class.active]="pageScrollSpyService.currentSpyItem === 'second'"
      >
        Second
      </a>
    </li>
    <li>
      <a 
        pageScroll 
        pageScrollSpy="third" 
        href="#third" 
        [class.active]="pageScrollSpyService.currentSpyItem === 'third'"
      >
        Third
      </a>
    </li>
  </ul>
</nav>

<div class="blocks">
  <!-- 给每个内容区块添加pageScrollSpyItem指令,值对应锚点名称 -->
  <div class="block" id="first" pageScrollSpyItem="first">First</div>
  <div class="block" id="second" pageScrollSpyItem="second">Second</div>
  <div class="block" id="third" pageScrollSpyItem="third">Third</div>
</div>

3. 组件中注入服务

在当前使用的组件中注入PageScrollService即可获取当前激活的锚点:

import { PageScrollService } from 'ngx-page-scroll-core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  constructor(public pageScrollSpyService: PageScrollService) {}
}

4. 可选配置调整

  • 如果顶部导航是固定定位,需要在模块导入的配置里调整scrollOffset参数,值为导航栏的高度,避免内容滚动后被导航遮挡
  • 可以调整spy触发阈值:给内容区块的pageScrollSpyItem添加[threshold]="0.5",表示当区块50%进入视口时就触发对应导航激活
  • 如果需要默认选中default项,可在组件初始化时手动设置pageScrollSpyService.currentSpyItem = 'default',监听滚动事件当滚动距离小于第一个区块的偏移量时重置为default即可。

内容的提问来源于stack exchange,提问作者user16907356

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:54:06