单击一个按钮(这是页面的底部),我想转到当前页面顶部的某个元素(在我的例子中是#navbar),但是我不知道该如何做。我尝试了下面的代码,但没有结果。
<nav class="navbar navbar-light bg-faded" id="navbar">
<a class="navbar-brand" href="#">
{{appTitle}}
</a>
<!-- rest of the nav link -->
</nav>
<!-- rest of the page content -->
<!-- bottom of the page -->
<button class="btn btn-outline-secondary" (click)="gotoTop()">Top</button>在角部分:
import { Router } from '@angular/router';
/* rest of the import statements */
export class MyComponent {
/* rest of the component code */
gotoTop(){
this.router.navigate([], { fragment: 'navbar' });
}
}如果有人帮助我找到解决方案并解释为什么我的代码不起作用,我会非常感激的。
请注意元素(navbar)在其他组件中。
发布于 2017-08-17 18:33:13
您可以使用javascript来完成这一任务:
gotoTop() {
let el = document.getElementById('navbar');
el.scrollTop = el.scrollHeight;
}当调用该方法时,这将使带有id="navbar"的DOM元素进入视图。还可以选择使用Element.scrollIntoView。这可以提供一个平滑的动画,看上去不错,但不支持在旧浏览器。
如果元素位于不同的组件中,则可以引用几种不同的方式,如这个问题中所示。
对于您的情况,最简单的方法可能是:
import { ElementRef } from '@angular/core'; // at the top of component.ts
constructor(myElement: ElementRef) { ... } // in your export class MyComponent block最后
gotoTop() {
let el = this.myElement.nativeElement.querySelector('nav');
el.scrollIntoView();
}发布于 2017-08-18 18:05:56
我知道,您希望滚动到页面中的特定元素。但是,如果元素位于页面顶部,则可以使用以下方法:
window.scrollTo(0, 0);发布于 2021-04-01 11:14:34
document.getElementById("YOUR_DIV_ID").scrollIntoView({ behavior: 'smooth' });https://stackoverflow.com/questions/45742611
复制相似问题