使用 Javascript 自动滚动 <textarea>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3680476/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:55:24  来源:igfitidea点击:

Auto-scroll <textarea> with Javascript

javascripttextareaautoscroll

提问by Big Mo Fo

I have this textarea that shows inputted text, but when the number of lines exceeds the size and width of the textarea, the user has to scroll down to see what they have last inputted.

我有这个显示输入文本的 textarea,但是当行数超过 textarea 的大小和宽度时,用户必须向下滚动以查看他们最后输入的内容。

I'd like the textarea to be set to the bottom everytime the enter button is pressed.

我希望每次按下输入按钮时将 textarea 设置为底部。

I've tried the following, but I can't get it to work:

我尝试了以下操作,但无法正常工作:

function inputKeyDown(evt, input) {    
    if (evt.keyCode == 13) {    
        var textarea = document.getElementById("textarea");  
        textarea.value += "\n" + ">" + " " + input.value;  
        input.value = "";  
        return false;       
    }  
    var elem = document.getElementById('textarea');  
    elem.scrollTop = elem.scrollHeight;    
} 

and then I call the function keyDown in <input onKeyDown="return keyDown(event, this);" ...>

然后我调用函数 keyDown <input onKeyDown="return keyDown(event, this);" ...>

Any idea why no workie?

知道为什么没有workie吗?

回答by four33

Try the following:

请尝试以下操作:

textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;

回答by Yi Jiang

It depends on what sort of input you are looking at, but forcing the cursor back to the bottom could potentially be a serious usability problem. If you need a textarea that automatically expands, have a look at existing solutions such as this jQuery plugin

这取决于您正在查看的输入类型,但强制光标回到底部可能会导致严重的可用性问题。如果您需要一个自动扩展的文本区域,请查看现有的解决方案,例如这个jQuery 插件

I'm not really sure if this is what you want but have a look this: http://jsfiddle.net/yV76p/

我不确定这是否是你想要的,但看看这个:http: //jsfiddle.net/yV76p/

var textarea = document.getElementById("textarea");

textarea.onkeyup = function(evt) {
    this.scrollTop = this.scrollHeight;
}