【问题标题】:How Can I Make The Scroll Bar Stay At The Bottom When New Data Is Added添加新数据时如何使滚动条保持在底部
【发布时间】:2019-03-18 02:11:18
【问题描述】:

你好编码员!我正在编写一个聊天系统,我希望滚动条留在底部。这样,当有人发送消息时,用户不必向下滚动。我也希望它从页面加载的底部开始。此外,用户可以在需要时向上滚动,但当他们向下滚动时,它会锁定到位。我尝试了很多次,但由于某种原因它不起作用,我想知道是否有人有这样做的方法?

【问题讨论】:

  • 你能告诉我们你的尝试吗?
  • 你应该翻转结果,所以最新的在顶部:)
  • 或者你可以使用 scrollTop 和 document.offsetHeight
  • @UlrikMcArdle 你能否详细说明我已经尝试过来自:stackoverflow.com/questions/18614301/… 的方法。
  • 使用 let offsetHeight = document.querySelector('.chat-item').offsetHeight; 获取最后一个元素的位置(如果它在 af 聊天窗口中)然后在聊天窗口元素上使用 scrollTop - 我没有尝试过,但理论上它应该可以工作。

标签: javascript php html css


【解决方案1】:

这是我在项目中使用的。它适用于 IE、Edge、Firefox、Chrome 和 Opera。我不确定 Safari。

var a = document.querySelector('#divchat');
a.scrollIntoView(false);

希望对你有帮助。

【讨论】:

  • 用这个方法,你的css有什么用?
  • 宽度:100%;最大宽度:100%;边距底部:1rem;背景颜色:透明;
【解决方案2】:

这个问题有很多答案。

这是来自Automatically scroll down chat div的其中一个

该答案的要点是可以操纵变量 scrollHeight、scrollTop 和 clientHeight。

但基本上,向下滚动是使用container.scrollTop = container.scrollHeight;

【讨论】:

  • 相信我,我知道。这些方法都没有奏效。我将在您的链接帖子中添加一个链接。
【解决方案3】:

我也一直在努力实现这一点。我最终采用的方法依赖于使用MutationObservable

MutationObservable 允许观察元素内部的 DOM 变化,并在深度嵌套元素发生变化时执行一些操作(在您的情况下,例如,呈现新评论):

// chatContainer is reference to your chatContainer element
var isLocked = true;

var mutationObserver = new MutationObserver(() => {
    if (isLocked) {
        scrollToBottom();
    }
});

mutationObserver.observe(chatContainer, {
    childList: true,
    subtree: true,
    attributes: false,
});

这给了我一个回调,我可能不得不让 chatContainer 滚动到底部。

滚动到底部的实现可能是:

function scrollToBottom() {
    chatContainer.scrollTop = 99999999999;
}

要更改 isLocked 标志,我必须在 chatContainer 上监听用户滚动并相应地更新它:

var LOCK_OFFSET = 25; // how many pixels close to bottom consider scroll to be locked
chatContainer.addEventListener('scroll', handleUserScroll);

function handleUserScroll() {
    var scrollFromBottom =
        chatContainer.scrollHeight -
        chatContainer.scrollTop -
        chatContainer.clientHeight; // how many pixels user scrolled up from button of the chat container.

    isLocked = scrollFromBottom > LOCK_OFFSET; // set new isLocked. lock, if user is close to the bottom, and unlock, if user is far from the bottom. 
});

希望我已经解释了总体思路。这种方法对我来说很好。应该通过事件去抖动来改进用户滚动监听。并且不要忘记处理滚动事件和突变观察者订阅。

【讨论】:

    猜你喜欢
    • 2011-12-08
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多