简体   繁体   中英

Auto-scroll <textarea> with Javascript

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.

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

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);" ...> <input onKeyDown="return keyDown(event, this);" ...>

Any idea why no workie?

请尝试以下方法:

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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