Javascript Textarea 自动滚动到底部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26557593/
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
Textarea auto-scroll to the bottom
提问by BenjiWiebe
I have a textarea that I append data to with textarea.value += "more text\n";and I would like it to "stay" scrolled to the bottom, so it would always show the last line.
我有一个文本区域,我将数据附加到其中textarea.value += "more text\n";,我希望它“保持”滚动到底部,因此它始终显示最后一行。
I have read that I should do:
我读过我应该这样做:
var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;
But I tried that (http://jsfiddle.net/BenjiWiebe/mya0u1zo/) and I can't get it to work.
但我试过了(http://jsfiddle.net/BenjiWiebe/mya0u1zo/),但我无法让它工作。
What am I doing wrong?
我究竟做错了什么?
回答by celeritas
You need to set scrollTopeach time you append text:
scrollTop每次追加文本时都需要设置:
var textarea = document.getElementById('textarea_id');
setInterval(function(){
textarea.value += Math.random()+'\n';
textarea.scrollTop = textarea.scrollHeight;
}, 1000);
回答by David Spector
To answer the original question: since your string output ends with a newline, you should scroll before you output, not after (I keep my ids in an object called id):
要回答原始问题:由于您的字符串输出以换行符结尾,您应该在输出之前而不是之后滚动(我将我的 ID 保存在一个名为 id 的对象中):
function Output(Msg)
{
...
id.Log.scrollTop=id.Log.scrollHeight;
SetValue('Log',out);
}

