尝试使用以下语法滚动到锚链接.
<a [routerLink]="['./']" fragment="test">Testing</a>
Run Code Online (Sandbox Code Playgroud)
锚节点看起来像这样
<div id="test">
Run Code Online (Sandbox Code Playgroud)
单击时,浏览器地址栏显示#test片段,但不会自动滚动.知道它为什么不滚动?
Per*_*ges 18
基于@vsavkin解决方法并利用片段作为可观察(使用"@angular/core": "^2.3.1")提供:
class MyAppComponent implements OnInit{
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.fragment.subscribe(f => {
const element = document.querySelector("#" + f)
if (element) element.scrollIntoView()
})
}
}
Run Code Online (Sandbox Code Playgroud)
从 Angular 6.1 开始,有 anchorScrolling,路由器有:
在 app.module.ts 中设置
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled', // or 'top'
anchorScrolling: 'enabled',
scrollOffset: [0, 64] // [x, y] - adjust scroll offset
})
],
exports: [RouterModule]
Run Code Online (Sandbox Code Playgroud)html
<div id="test">
// contents goes here...
</div>
<a [routerLink]="['./']" fragment="test">Testing</a>
Run Code Online (Sandbox Code Playgroud)现在导入 Angular v6 新功能的 viewScroller(这可能不是必需的):
import { ViewportScroller } from '@angular/common';
constructor( private viewportScroller: ViewportScroller )
...
scrollToTest() {
this.viewportScroller.scrollToAnchor('test');
}
Run Code Online (Sandbox Code Playgroud)这是带有额外配置的/sf/answers/3669104841/的扩展onSameUrlNavigation: 'reload'
完整示例:
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled', // or 'top'
anchorScrolling: 'enabled',
scrollOffset: [0, 64], // [x, y] - adjust scroll offset
onSameUrlNavigation: 'reload'
})
],
exports: [RouterModule]
Run Code Online (Sandbox Code Playgroud)
<p>
<div id = "componentId"> </div>
</p>
Run Code Online (Sandbox Code Playgroud)
onScrollTo(location: string){
setTimeout(() => { this.router.navigate([], { fragment: location }); }, 500);
}
use this method on Button click.
Run Code Online (Sandbox Code Playgroud)
我使用这种方法在同一页面上滚动。1.component.ts
scrollTo(fragment): void {
this.router.navigate([], { fragment: fragment }).then(res => {
const element = document.getElementById(fragment);
if (element != undefined) element.scrollIntoView();
});
}
Run Code Online (Sandbox Code Playgroud)
2.component.html
<section id="some-section">
<div></div>
....
</section>
Run Code Online (Sandbox Code Playgroud)
3.调用方法
<a (click)="scrollTo('some-section')">Navigate to Fragment</a>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10747 次 |
| 最近记录: |