简体   繁体   English

如何使具有动态内容的div自动滚动到底部?

[英]How to make a div with dynamic content automatically scroll to the bottom?

I have googled around and found a few solutions to this problem, but none of them seem to work in my situation. 我四处搜寻,找到了一些解决此问题的方法,但在我的情况下似乎都没有用。 I have tried hidden inputs to scroll to, that stay at the bottom 我尝试过将隐藏的输入滚动到底部

document.getElementById('scrollToMe').scrollIntoView();

I have tried 我努力了

$("#postbox").scrollTop($("#postbox")[0].scrollHeight);

and a few others. 和其他一些。 Here is my situation 这是我的情况

I have a chat room ( http://novaplasm.topiacloud.com/Chat ). 我有一个聊天室( http://novaplasm.topiacloud.com/Chat )。 When you type anything, it enters it into the div "postbox" using Knockout. 当您键入任何内容时,它会使用Knockout将其输入到div“邮箱”中。 Every time you enter new content, it appends it. 每次您输入新内容时,它都会附加它。 I want to make it so you can always see the latest message, without having to scroll yourself. 我要这样做,以便您始终可以看到最新消息,而不必滚动自己。 I can't seem to do this for the life of me. 我似乎一生都无法做到这一点。 Thanks in advanced! 提前致谢!

First get a reference to your postbox and chat message div 首先获取对您的邮箱和聊天消息div的引用

   var pbox = $('#postbox');

   var chat_div = $('<div></div>').attr('class', 'chat_msg').text(msg);

Here msg is your chat message msg是您的聊天消息

Then you have to scroll down using the 'animate' method like this 然后您必须使用“动画”方法向下滚动

  chat_div.appendTo(pbox);

   var height = pbox.scrollTop() + pbox.height() +  $('#postbox').filter('.chat_msg:last').scrollTop();

   pbox.animate({'scrollTop' : height}, 1000);

Here the animation is happening over 1 sec. 此处的动画发生时间超过1秒。

Refer jQuery documentation for more detailed explanations on jQuery methods. 有关jQuery方法的更多详细说明,请参考jQuery文档。

Live fiddle example 现场小提琴示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM