How to scroll element into view when it's clicked

梦想的初衷 提交于 2019-11-28 13:24:25

Please take a look at this working plunker

You can use the scrollTo(x,y,duration) method (docs). The code is pretty simple, first we obtain the position of the target element (a <p></p> in this case) and then we use that in the scrollTo(...) method. First the view:

<ion-header>
  <ion-navbar primary>
    <ion-title>
      <span>My App</span>
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <button ion-button text-only (click)="scrollElement()">Click me</button>

  <div style="height: 600px;"></div>

  <!-- Notice the #target in the p element -->
  <p #target>Secret message!</p>

  <div style="height: 600px;"></div>

</ion-content>

And the component code:

import { ViewChild, Component } from '@angular/core';
import { NavController, Content } from 'ionic-angular';

@Component({
  templateUrl:"home.html"
})
export class HomePage {
  @ViewChild(Content) content: Content;
  @ViewChild('target') target: any;

  constructor() {   }

  public scrollElement() {
    // Avoid reading the DOM directly, by using ViewChild and the target reference
    this.content.scrollTo(0, this.target.nativeElement.offsetTop, 500);
  }
}

I'd use an anker link in HTML.

Just give the elemnt and id="scrollXYZ" and wrap the button in an

Example:

<a href="#scrollXYZ"><button>Example</button></a>
<div id="scrollXYZ"><h2>Scroll to this</h2></div>

I noticed the above solution don't work well with Angular Universal server-side rendering (SSR) due to document not being available server-side.

Hence I wrote a convenient plugin to achieve scrolling to elements in Angular 4+ that work with AoT and SSR

NPM
ngx-scroll-to

GitHub
ngx-scroll-to

I was trying to do this in Ionic 3 and due to the fact that <Element>.offsetTop was returning10 (the padding on the top of the element) instead of the distance to the top of the page (much larger unknown number) I ending up just using <Element>.scrollIntoView(), which worked well for me.

To get the <Element> object I used document.getElementById(), but there are many other options on how to get a handle on that.

In Ionic 4 the scroll function is renamed to scrollToPoint().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!