Angular4-滚动到锚点 [英] Angular4 - Scrolling to anchor
问题描述
我正在尝试简单滚动到同一页面上的锚点元素.基本上,此人单击尝试"按钮,然后滚动到ID为登录"的页面下方区域.目前,它正在使用基本的id="login"
& <a href="#login"></a>
,但它跳到该部分.理想情况下,我希望它滚动到那里.如果我使用的是Angular4,是否有内置的方法可以做到这一点,或者最简单的方法是什么?谢谢!
I am trying to do a simple scroll to an anchor element on the same page. Basically, the person clicks on a "Try It" button and it scrolls to an area lower on the page with the id "login". Right now, it is working with a basic id="login"
& <a href="#login"></a>
but it is jumping to that section. Ideally, I would like it to scroll there. If I am using Angular4, is there some built in way to do this or what is the easiest way? Thanks!
整个模板...(组件仍为空)
Whole template... (component still empty)
<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>
推荐答案
对于Angular 6+,您可以使用:
For Angular 6+ you can use:
-
在您的路由模块中:
In your routing module:
imports: [RouterModule.forRoot(routes, { anchorScrolling: 'enabled'})]
然后在组件html中
Then in your component html
<a (click)="onClick('AnchorId')">Click me!</a>
<a (click)="onClick('OtherAnchorId')">Click me, too!</a>
...
<div id="AnchorId">...</div>
...
<div id="OtherAnchorId">...</div>
然后在组件ts
Then in your component 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);
}
}
这篇关于Angular4-滚动到锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!