Javascript 强制滚动条到底部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7063627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force scrollbar to bottom
提问by grep
I am making a little messaging / chat system that is working nice and fine. The problem is, the <div>which the messages are outputted to does not scroll the way I need it to.
我正在制作一个运行良好的小消息/聊天系统。问题是,<div>消息输出到的内容并没有按照我需要的方式滚动。
All the new messages are added to the bottom of the div and when more are added and the scrollbar shows up, the scrolling stays at the top of the <div>. I need this to be reversed, so that the scrolling always sticks to the bottom of the <div>.
所有新消息都添加到 div 的底部,当添加更多消息并显示滚动条时,滚动保持在<div>. 我需要将其反转,以便滚动始终保持在<div>.
A good example of what I want would be Steam's chat windows, or even this text input which I am using to fill out the question.
我想要的一个很好的例子是Steam 的聊天窗口,甚至是我用来填写问题的文本输入。
As I would like to avoid jQuery, this has me completely stuck. If you could point me in the correct direction that would be great! I am not sure if HTMLand CSScan handle this, or if JavaScriptis necessary at all.
由于我想避免jQuery,这让我完全陷入困境。如果你能指出我正确的方向,那就太好了!我不确定HTML和CSS 是否可以处理这个问题,或者是否需要JavaScript。
回答by michaelx386
The Javascript code below should keep your div's scrollbar positioned at the bottom like you described:
下面的 Javascript 代码应该使您的 div 滚动条像您描述的那样位于底部:
var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;
This solution and more information can be found on the link below: http://web.archive.org/web/20080821211053/http://radio.javaranch.com/pascarello/2005/12/14/1134573598403.html
此解决方案和更多信息可以在以下链接中找到:http: //web.archive.org/web/20080821211053/http: //radio.javaranch.com/pascarello/2005/12/14/1134573598403.html
回答by Rodan Sotto
I think this is a better solution:
我认为这是一个更好的解决方案:
element.scrollTop = element.scrollHeight - element.clientHeight;

