2016-12-27 81 views
3

我想滚动到离子2中的listview中的特定项目。我有一个绑定到数组的listview。滚动到离子2中的特定项目LisdiVew

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)本身?我如何获得item no 150的位置并将其传递给scrollTo?

+1

我不知道,如果你解决了这个。在我看文档的时候,没有“scrollToItem”,尽管你可以使用你的approxItemHeight和item的索引来计算位置,并使用'ionContent.scrollTo(0,approxItemHeight * index);'如果你有页眉或页脚不要忘记计算它们的高度,并将其添加到您的计算中 – Patrick

回答

1

我张贴的解决方案,我想出了(查看完整的实现here)。首先,你需要GI已经唯一ID到每个列表视图项,然后选择ListView

@ViewChild(VirtualScroll) listView: VirtualScroll; 

之后我创建的函数(下列)ScrollTo,其具有(动态,因为我正在改变缓冲器比)滚动太后调整列表视图的超时。

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

最后我只是把这种功能的第二延迟后,我等待着,直到列表视图载荷:

//must be delay otherwise content scroll doesn't go to element properly..magic! 
setTimeout(() => { 
    this.scrollTo('someId'); 
}, 1000); 
5

您可以将ID分配给每个项目(通过执行类似[id]="'item' + item.index",然后在你的代码,只需使用该ID来获得offsetTop

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

但我需要在ionViewWillEnter触发时立即滚动。我目前没有在视图中 –

+0

您可以使用'ionViewDidLoad'来确保内容已经被加载,并获得像上面代码中所做的'offsetTop'。因此,不要创建一个新方法,只需将该代码放入'ionViewDidLoad'生命周期事件中即可。 – sebaferreras

+1

听起来不错。将尝试这个 –

3

目前接受的答案只有滚动相对于父元素,所以这里是我想出了滚动到选定的元素(不遍历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); 
    } 
+0

谢谢,它的工作,只有有一些小的位置计算错误,如果页面有一个头,在我的情况。 – fifth