【问题标题】:How to force scroll in overflow-y div如何在overflow-y div中强制滚动
【发布时间】:2019-01-02 12:05:18
【问题描述】:

我正在尝试在包含 ngfor 列表的 div 中强制进行偏移滚动

我在作为overflow-y的div上试过这个:

@ViewChild('list') listRef: ElementRef;

然后点击我用一些日志尝试这个以确保它被调用

this.listRef.nativeElement.offsetTop = 500;

什么都没有发生,知道我怎么能做到这一点吗?

编辑:

HTML:

<div
  #gridContainerId
  class="gridContainer">
  <a *ngFor="let item of images;">
     <img src="{{getImage(item)}}"/>
  </a>
</div>

css:

.gridContainer {
  height: 90vh;
  overflow-y: scroll;
}

组件:

@ViewChild('gridContainerId') ref: ElementRef;

this.store.pipe(
      select(fromImages.getImages),
      takeWhile(() => this.componentActive)
    ).subscribe(imagesItems => {
        this.images = imagesItems;
        updateScroll();
      }
    );

updateScroll(){
  this.ref.nativeElement.scrollTop = this.ref.nativeElement.scrollHeight;
}

【问题讨论】:

    标签: javascript html angular typescript ngfor


    【解决方案1】:

    我最近在你的同样场景中,当点击某个按钮时,div 滚动到底部,我用这个代码实现了它:

    this.messagesContainer.nativeElement.scrollTop = this.messagesContainer.nativeElement.scrollHeight;
    

    属性scrollTop是指定从视图顶部滚动的像素数。
    而属性scrollHeight是获取div的总高度。

    【讨论】:

    • 我在有溢出的容器上试过了,没有任何反应:/
    • 我猜这里的问题是您在视图渲染之前滚动,您需要在 setTimeout 中添加它以便在视图渲染后执行并获取其实际高度
    • 我可以共享一些代码,但我不能包含所有内容,我必须重命名它。保密问题。
    • 我尝试了 2000 毫秒超时相同的结果没有任何反应,列表在不到 100 毫秒的时间内加载和呈现
    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 2015-03-25
    • 2017-12-21
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    相关资源
    最近更新 更多