asm*_*mud 4 javascript angular2-routing angular
单击一个按钮(页面底部),我想转到当前页面顶部的某个元素(在我的情况下,#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>
Run Code Online (Sandbox Code Playgroud)
在角度分量中:
import { Router } from '@angular/router';
/* rest of the import statements */
export class MyComponent {
/* rest of the component code */
gotoTop(){
this.router.navigate([], { fragment: 'navbar' });
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人帮我解决问题并解释了为什么我的代码无效,我将非常感激.
请注意,元素(navbar)位于其他组件中.
你可以用javascript做到这一点:
gotoTop() {
let el = document.getElementById('navbar');
el.scrollTop = el.scrollHeight;
}
Run Code Online (Sandbox Code Playgroud)
这将在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
Run Code Online (Sandbox Code Playgroud)
最后
gotoTop() {
let el = this.myElement.nativeElement.querySelector('nav');
el.scrollIntoView();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14941 次 |
| 最近记录: |