ScrollTo particular item of ListiVew in Ionic 2

你离开我真会死。 提交于 2019-12-03 06:46:13

You can assign an id to each item (by doing something like [id]="'item' + item.index" and then in your code just use that id to get the offsetTop:

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

The current accepted answer only scrolled relative to the parent element, so here is what I came up with to scroll to the selected element (without traversing the 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);
  }

I am posting the solution i come up with. First you need to give unique id to each listview item and then select the ListView

@ViewChild(VirtualScroll) listView: VirtualScroll;

After that i created a function (following) ScrollTo which has a timeout of resizing the listview after scrolling too (as i was changing buffer ratio dynamically).

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

Last i just called this function after a second delay as i waited till listview loads:

//must be delay otherwise content scroll doesn't go to element properly..magic!
setTimeout(() => {
    this.scrollTo('someId');
}, 1000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!