Angular - 展开子元素时保持 div 的滚动条位置

问题描述 投票:0回答:1

我有一个 DIV 容器,在实践中可以充当日志容器。它具有

overflow: auto
并具有
flex-direction: column-reverse
以按时间顺序从下到上显示日志条目。

我将这些日志条目作为 JSON 结构,并提取消息本身的文本

line.text
,如果可用,则使用
line.JSON
提取另一个 JSON 结构。如果存在 JSON 结构,则会显示一个按钮,通过该按钮可以显示或隐藏相应的
<pre>
元素,在该元素中可以看到格式化的 JSON 代码。

现在我遇到的问题是,当我使用按钮展开日志条目时,文本向上移动,最终到达

<pre>
元素的底部。出于可用性原因,这很糟糕。这可能是由于 CSS 属性
column-reverse

预期的行为是滚动条向下展开,并且您不会丢失按钮上的视图。因此,除了这个元素向底部展开之外,用户在视觉上没有任何变化。

我已经尝试过将“scrollTop”位置设置为按钮的高度,但这也是一个相当烦人的行为。

if(logContainer && button) {
    logContainer.scrollTop = button.offsetTop - logContainer.offsetTop; 
}

所以我的问题是:我如何操纵滚动条行为来满足这些要求?

我在 Stackblitz 上创建了一个最小的复制示例:这里

html css angular scroll
1个回答
0
投票
toggleJsonDisplay(index: number) {
    //toggle node expansion (but the change isn't rendered yet!)
    this.showJsonMap[index] = !this.showJsonMap[index];

    const logContainer = this.logContainer.nativeElement;
    const button = document.getElementById(`jsonDisplayButton${index}`);

    //get current offsetTop of the button relative to the container
    const originalOffsetTop = button.offsetTop;
    setTimeout(() => {
      //in this context the UI will update because of the event loop!
      //get new offsetTop of the button relative to the container
      const newOffsetTop = button.offsetTop;
      //calc the difference between those
      const offsetDifference = newOffsetTop - originalOffsetTop;
      //and change the scrollTop of the container accordingly
      logContainer.scrollTop += offsetDifference;
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.