Angular4 - 滚动到锚点

lna*_*mba 23 html css anchor-scroll angular

我试图在同一页面上做一个简单的滚动到一个锚元素.基本上,该人点击"试一试"按钮,它会滚动到页面下方的区域,其ID为"登录".现在,它正在使用一个基本的id="login",<a href="#login"></a>但它跳到那个部分.理想情况下,我希望它滚动到那里.如果我使用的是Angular4,是否有一些内置方法可以做到这一点或者最简单的方法是什么?谢谢!

整个模板......(组件仍然是空的)

<div id="image-header">
    <div id="intro">
        <h1 class="text-center">Welcome to ThinkPlan</h1>
        <h3 class="text-center">Planning your way</h3>
        <a class="btn btn-outline-primary" href="#login" id="view">Try It</a> <!-- Where the user clicks to scroll -->
    </div>
</div>
<div class="container" id="info">
    <div class="row">
        <div class="col-md-12">
             <div class="space" id="login"></div> <!-- The place to scroll to -->
                <h1 class="text-center">ThinkPlan</h1>
                <form  class="form-horizontal">
                    <fieldset>
                        <legend>Login</legend>
                        <div class="form-group">
                            <label for="inputEmail" class="col-lg-2 control-label">Email</label>
                            <div class="col-lg-10">
                                <input type="text" class="form-control" id="inputEmail" placeholder="Email">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword" class="col-lg-2 control-label">Password</label>
                            <div class="col-lg-10">
                                <input type="password" class="form-control" id="inputPassword" placeholder="Password"> 
                            </div>
                        </div>
                        <div class="form-group" id="log-btn">
                            <div class="col-lg-10 col-lg-offset-2">
                                <button routerLink="/plan" type="submit" class="btn btn-outline-primary">Login</button>
                            </div>
                        </div>
                        <p class="lead text-center">New here? <a routerLink="signup">Sign up.</a></p>
                    </fieldset>
                </form>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

0lu*_*sz0 51

对于 Angular 6+,您可以使用:

  1. 在您的路由模块中:

     imports: [RouterModule.forRoot(routes, { anchorScrolling: 'enabled'})]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 然后在你的组件 html

     <a (click)="onClick('AnchorId')">Click me!</a>
     <a (click)="onClick('OtherAnchorId')">Click me, too!</a>
     ...
     <div id="AnchorId">...</div>
     ...
     <div id="OtherAnchorId">...</div>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 然后在你的组件 ts

    import { ViewportScroller } from '@angular/common';
    
    @Component({
        selector: 'component-selector',
        templateUrl: './mycomponent.component.html'
    })
    export class MyComponent {
      constructor(private viewportScroller: ViewportScroller) {}
    
      public onClick(elementId: string): void { 
          this.viewportScroller.scrollToAnchor(elementId);
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 尽管 Kim Kern 的答案是正确的,但这感觉更像是“Angular 框架”。你还可以添加 css: "html {scroll-behavior: smooth;}" 使其更愉快。 (6认同)
  • 不错,但你不需要导入: [RouterModule.forRoot(routes, {anchorScrolling: 'enabled'})] viewportScroller 不需要 routermodule 作为依赖项 (3认同)

小智 18

我认为这是更简单的解决方案:

在您的HTML中:

<a [routerLink]="['/']" fragment="login"></a>
Run Code Online (Sandbox Code Playgroud)

在你的打字稿中:

ngOnInit() {
 this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}

ngAfterViewChecked(): void {
  try {
      if(this.fragment) {
          document.querySelector('#' + this.fragment).scrollIntoView();
      }
  } catch (e) { }
}
Run Code Online (Sandbox Code Playgroud)

  • 这重定向到根路由。要在同一页面位置添加哈希,使用 `&lt;a routerLink="." 效果更好。fragment="登录"&gt;&lt;/a&gt;`。 (4认同)
  • 你可以像这样顺利滚动:`scrollIntoView({behavior:"smooth"})` (4认同)
  • 呃,什么是`this.route`?? (3认同)
  • @SarahDubois,这是一个非常好的解决方案,对于使用 Angular 版本 8 的我来说效果很好。五颗星是因为它的简单性。@Phil `this.route` 是ActivatedRoute。您可能需要这些导入 `import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';` 我可以发布包含更多详细信息的答案。 (3认同)

Kim*_*ern 15

自动滚动

从Angular v6开始,有了新anchorScrolling选项RouterModule。您可以在模块的导入中进行设置:

imports: [
  ...,
  RouterModule.forRoot(routes, {anchorScrolling: 'enabled'})
Run Code Online (Sandbox Code Playgroud)

这样,Angular将自动滚动到具有给定片段ID的元素。

?? 但是,当异步加载数据时,这不起作用,请参阅此Github问题。??


手动滚动

尚无法通过进行平滑滚动RouterModule,但您可以手动进行滚动

1)获得目标,例如ViewChild

@ViewChild('pageInfo') pageInfo: ElementRef; 
Run Code Online (Sandbox Code Playgroud)

2)调用scrollIntoViewnativeElement

const targetElement = this.pageInfo.nativeElement
targetElement.scrollIntoView({behavior: "smooth"})
Run Code Online (Sandbox Code Playgroud)


Til*_*ilo 5

现代单线解决方案:

export class Component implements AfterViewInit {

  constructor(
    private viewportScroller: ViewportScroller
  ) { }

  ngAfterViewInit(): void {
    this.route.fragment.pipe(
      first()
    ).subscribe(fragment => this.viewportScroller.scrollToAnchor(fragment));
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 3

使用 Angular 4,您在使用锚点到同一页面时可能会遇到一些问题。

我用这种方式解决了

ng2 页面滚动

安装

npm install ng2-page-scroll --save
Run Code Online (Sandbox Code Playgroud)

导入你的 app.module.ts

import {Ng2PageScrollModule} from 'ng2-page-scroll';

@NgModule({
    imports: [
        /* Other imports here */
        Ng2PageScrollModule
        ]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)

在你的 html 组件中测试它

<a pageScroll href="#test">Testing</a>
<div id="test">
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供这个全面的答案,我尝试了一下,但是 npm 模块已经过时了最新的 Angular 版本的对等依赖关系。 (2认同)