在Angular 4中滚动到当前页面的某个元素 [英] Scroll to a certain element of the current page in Angular 4

查看:117
本文介绍了在Angular 4中滚动到当前页面的某个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮(位于页面底部)后,我想转到当前页面顶部的某个元素(在我的情况下为#navbar),但我不知道如何做吧.我已经尝试了以下代码,但无济于事.

Upon clicking a button (which is bottom of the page), I want to go to a certain element (in my case, #navbar) which is in the top of the current page, but I don't know how to do it. I've tried the following code with no avail.

<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' });
    }
}

如果有人帮助我提供解决方案并解释为什么我的代码无法正常工作,我将不胜感激.

I would really appreciate if someone helped me out with a solution and explained why my code hadn't worked.

请注意,元素(navbar)在其他组件中.

Please note that element (navbar) is in other component.

推荐答案

您可以使用javascript:

You can do this with javascript:

gotoTop() {
  let el = document.getElementById('navbar');
  el.scrollTop = el.scrollHeight;
}

在调用该方法时,将带id="navbar"的DOM元素显示出来.还可以选择使用 Element.scrollIntoView .这样可以提供平滑的动画,看起来不错,但是旧版浏览器不支持.

This will bring the DOM element with id="navbar" into view when the method is called. There's also the option of using Element.scrollIntoView. This can provide a smooth animation and looks nice, but isn't supported on older browsers.

如果该元素位于其他组件中,则可以通过几种不同的方式引用该元素,如

If the element is in a different component you can reference it several different ways as seen in this question.

适合您的案例的最简单方法可能是:

The easiest method for your case would likely be:

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();
}

工作中的矮人.

这篇关于在Angular 4中滚动到当前页面的某个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆