如何在单击时将元素滚动到视图中 [英] How to scroll element into view when it's clicked

查看:279
本文介绍了如何在单击时将元素滚动到视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似于 scrollIntoView(例如,当我点击一个按钮时,Ionic2中的

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

ion-content 帮助。

推荐答案

请看一下 这个工作的plunker

Please take a look at this working plunker

你可以使用 scrollTo(x ,y,持续时间)方法(docs)
代码非常简单,首先我们获取目标元素的位置(在这种情况下为< p>< / p> )然后我们在 scrollTo(...)方法中使用它。首先是观点:

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>

组件代码:

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

这篇关于如何在单击时将元素滚动到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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