我有一个div,只有300像素大,我希望它在页面加载时滚动到内容的底部。这个div有动态添加的内容,需要一直向下滚动。现在如果用户决定向上滚动,我不希望它跳回底部,直到用户再次向下滚动

是否有可能有一个div,将保持滚动到底部,除非用户向上滚动,当用户滚动回底部时,它需要保持自己在底部,即使添加了新的动态内容。我该怎么做呢。


当前回答

以下是我的做法。div的高度是650px。我决定如果滚动高度在底部的150px范围内,那么自动滚动它。否则,留给用户。

if (container_block.scrollHeight - container_block.scrollTop < 800) {
                    container_block.scrollTo(0, container_block.scrollHeight);
}

其他回答

//Make sure message list is scrolled to the bottom
var container = $('#MessageWindowContent')[0];
var containerHeight = container.clientHeight;
var contentHeight = container.scrollHeight;

container.scrollTop = contentHeight - containerHeight;

以下是我基于dotnetCarpenter回答的版本。我的方法是一个纯jQuery和我命名的变量,使事情更清楚一点。发生的情况是,如果内容高度大于容器高度,我们向下滚动额外的距离以实现所需的结果。

工作在IE和chrome..

$('#yourDivID').animate({ scrollTop: $(document).height() }, "slow");
return false;

这将使用$(document).height()属性从#yourDivID的高度计算滚动顶部位置,这样即使在div中添加了动态内容,滚动条也将始终位于底部位置。希望这能有所帮助。但它也有一个小错误,即使我们向上滚动并将鼠标指针从滚动条上保留下来,它也会自动回到底部位置。如果有人能纠正这一点,那就太好了。

这个问题有原生的支持。

有一个叫做*. scrollintoview的方法。 在运行此方法一次之后,它将容器滚动保持在底部。 即使在容器中添加了新内容,它也会滚动到底部。

import {
  AfterViewInit,
  Directive,
  ElementRef,
} from '@angular/core';

@Directive({
  selector: '[aeScrollIntoView]',
})
export class ScrollIntoViewDirective implements AfterViewInit {
  constructor(private readonly el: ElementRef<HTMLDivElement>) {}
  ngAfterViewInit(): void {
    this.el.nativeElement.scrollIntoView({ behavior: 'smooth' });
  }
}

<div aeScrollIntoView>
 Your long and dynamic content. 
 Whenever new content is added to this container, it scrolls to the bottom.
<div>

以下是我的做法。div的高度是650px。我决定如果滚动高度在底部的150px范围内,那么自动滚动它。否则,留给用户。

if (container_block.scrollHeight - container_block.scrollTop < 800) {
                    container_block.scrollTo(0, container_block.scrollHeight);
}

与Bootstrap 5:

< span style=" font - family:宋体;max-height: 300 px;" > < div > <!——你这里的内容——> < / div > < / div >