滚动到Ionic 2中ListiVew的特定项目

时间:2016-12-27 04:50:10

标签: angular typescript ionic-framework ionic2 ionic3

我想滚动到离子2中列表视图中的特定项目。我有一个列表视图绑定到数组。

export class TestPage {
    @ViewChild(Content) content: Content;
    public items: Array<Object> = [];

    ionViewWillEnter() {
        console.log(this.navParams.data);
        this.customService.getArray(this.params.index).then((items) => {
            this.items = items;
                //scroll to item
                // this.content.scrollTo()
        });
     }
}

以下是观点:

<ion-list [virtualScroll]="items" approxItemHeight="120px" approxItemWidth="100%" 
    class="items-listview list list-md">
  <button class="items-listview-item item item-md" *virtualItem="let item">
    <div class="items-listview-text">
        {{ item.text }}<span>{{item.index}}</span>
    </div>
  </button>
</ion-list>

我看到scrollTo仅支持位置,即顶部和左侧,但不支持元素本身。如何滚动列表视图项目(例如项目编号150)本身?如何获得项目编号的位置并将其传递给scrollTo?

3 个答案:

答案 0 :(得分:5)

您可以为每个项目分配一个ID(通过执行类似[id]="'item' + item.index"的操作,然后在您的代码中使用该ID来获取offsetTop

scrollTo(elementId:string) {
    let yOffset = document.getElementById(elementId).offsetTop;
    this.content.scrollTo(0, yOffset, 4000)
}

答案 1 :(得分:4)

当前接受的答案只相对于父元素滚动,所以这就是我想出来滚动到所选元素(不遍历DOM)。

  scrollTo(element:string) {
    let elem = document.getElementById(element);
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docEl = document.documentElement;

    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var clientTop = docEl.clientTop || body.clientTop || 0;
    var top  = box.top +  scrollTop - clientTop;
    var cDim = this.content.getContentDimensions();

    var scrollOffset = Math.round(top) + cDim.scrollTop - cDim.contentTop;

    this.content.scrollTo(0, scrollOffset, 500);
  }

答案 2 :(得分:2)

我发布了我想出的解决方案。首先,您需要为每个列表视图项提供唯一ID,然后选择$first = $_POST['first_name']; $last = $_POST['last_name']; $message = $_POST['message']; $email = "Name: " . $first . " Last name: " . $last . " Message: " . $message; $to = "youremail@yourdomain.com"; $subject = "New message from " . $first . " " . $last; $body = $email; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $body, $headers );

ListView

之后我创建了一个函数(跟随)@ViewChild(VirtualScroll) listView: VirtualScroll; ,它在滚动之后超时调整listview的大小(因为我动态地改变了缓冲区比率)。

ScrollTo

最后我在第二次延迟后调用此函数,因为我等到listview加载:

private scrollTo(index: number) {
    let key = '#customIds_' + index;

    let hElement: HTMLElement = this.content._elementRef.nativeElement;
    let element = hElement.querySelector(key);
    element.scrollIntoView();

    //wait till scroll animation completes
    setTimeout(() => {
        //resize it! otherwise will not update the bufferRatio
        this.listView.resize();
    },500);
}