How to have a textarea to keep scrolled to the bot

2019-01-11 13:27发布

My problem is a bit off the cuff here, so I'll try to explain this best I can.

I have a text area, having css of #object{overflow:hidden;resize:none;}. I am trying to prevent it from spawning scroll bar while also resizing itself. This textarea is synced with an external script's console meaning it updates. By default however, it will stay at the top unless you highlight text, dragging off to the bottom of the element. This would be the only way to scroll down other than with arrow keys, naturally.

Programmatically, is there any way to keep the text area down to the bottom upon updating? It would be nice to have it auto-scroll to accommodate its use case.

5条回答
狗以群分
2楼-- · 2019-01-11 13:44

Using Javascript

var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;

Using Jquery

$('#textarea_id').scrollTop($('#textarea_id')[0].scrollHeight);​​​
查看更多
Root(大扎)
3楼-- · 2019-01-11 13:53

You can do it by javascript. Set the scrollTop property of text area with scrollHeight property like below:

document.getElementById("textarea").scrollTop = document.getElementById("textarea").scrollHeight 
查看更多
SAY GOODBYE
4楼-- · 2019-01-11 13:55

Generic JQuery Plugin

Here a generic jquery plugin for scrollBottom of any element:

$.fn.scrollBottom = function() {
  return $(this).scrollTop($(this)[0].scrollHeight);
};

usage:

$("#logfile").val( $("#logfile").val() + "this is new line test\n" ).scrollBottom();
查看更多
仙女界的扛把子
5楼-- · 2019-01-11 14:05

By using jQuery, you can find out when the content of the textarea changes using:

$("#object").change(function() {
  scrollToBottom();
});

And scroll to the bottom using:

function scrollToBottom() {
  $('#object').scrollTop($('#object')[0].scrollHeight);
}

Scroll code taken from jquerybyexample.blogspot.com.

查看更多
Ridiculous、
6楼-- · 2019-01-11 14:05
function checkTextareaHeight(){
   var textarea = document.getElementById("yourTextArea");
   if(textarea.selectionStart == textarea.selectionEnd) {
      textarea.scrollTop = textarea.scrollHeight;
   }
}

Call this function every time when the contents of the textarea are changed. If you cannot edit the external influence, periodically activate this function using setInterval.

查看更多
登录 后发表回答