2016-09-08 57 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

相关问题