How to scroll element into view when it's clicked

前端 未结 7 1839
甜味超标
甜味超标 2020-12-11 02:30

Am looking for something similar to scrollIntoView() within Ionic2 to use when I click on a button, for example.

None of the methods detailed in ion-content help.

相关标签:
7条回答
  • 2020-12-11 03:01

    For Ionic-4 there are multiple changes in the terms used

    1. Content is changed to IonContent
    2. scrollTo is changed to scrollToPoint
    3. ionic-angular is changed to @ionic/angular
    4. viewChild has to have { static: false } // only if you are using angular >8.0

    Here is the code modified of the accepted answer for ionic-4

    <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(target)">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>
    

    component Code :

    import { ViewChild, Component } from '@angular/core';
    import { IonContent } from '@ionic/angular'; // change-1
    
    @Component({
      templateUrl:"home.html"
    })
    export class HomePage {
       @ViewChild('target', { static: false }) target: ElementRef;
       @ViewChild('ion_content', { static: false }) ionContent: IonContent; //change-2 for angular > 8.0 remove this for angular 6.x
    
      constructor() {   }
    
      public scrollElement($target) {
        this.ionContent.scrollToPoint(0, $target.offsetTop, 500); 
        //$target (prefered if you have multiple scroll target) could be this.target.nativeElement
      }
    }
    
    0 讨论(0)
提交回复
热议问题