2016-09-08 49 views

回答

8

請看看this working plunker

可以使用scrollTo(x,y,duration)方法(docs)。代碼非常簡單,首先我們獲取目標元素的位置(在這種情況下爲<p></p>),然後我們在scrollTo(...)方法中使用它。首先查看:

<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> 

和組件代碼:

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); 
    } 
} 
+1

的鏈接plunker沒有按似乎沒有顯示與答案有關的任何內容。 – Willwsharp

+1

我很抱歉@Willwsharp,闖入者使用了舊版本的Ionic。我今天晚些時候會創建一個新的重擊器:) – sebaferreras

+1

@Willwsharp我已經更新了答案,以避免直接讀取DOM。現在它使用'ViewChild'來獲取HTML元素的引用 – sebaferreras

1

我會使用HTML中的安克鏈接。

只要給elemnt和id =「scrollXYZ」和包裹按鈕在

例子:

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

如果元素是動態添加的,這將不起作用 – Mackelito

+0

@Mackelito它會動態地添加scrollTo。 –

0

我注意到上述溶液不與角通用服務器端渲染很好地工作(SSR)由於document服務器端不可用。

因此,我寫了一個方便的插件來實現滾動到角4+與AoT工作,SSR

元素NPM
ngx-scroll-to

GitHub的
ngx-scroll-to

相關問題