如何将文本区滚动条设置为默认的底部?

我有一个文本区,正在动态重新加载用户输入正在发送。每隔几秒就会刷新一次。当文本区域中的文本数量超过文本区域的大小时,将出现一个滚动条。然而,滚动条实际上并不可用,因为如果你开始向下滚动,几秒钟后,文本区刷新,并将滚动条带回到顶部。我想设置滚动条默认显示最底部的文本。有人知道怎么做吗?

117091 次浏览

非常简单,用普通的 javascript:

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

您可以在 jQuery 中使用它

$(document).ready(function(){
var $textarea = $('#textarea_id');
$textarea.scrollTop($textarea[0].scrollHeight);
});

我遇到了同样的问题,发现没有属性可以在初始设置时获得正确的滚动行为。 但是,一旦在 textArea 中更新了文本,紧接着在同一个函数中,可以将 focus ()设置为 textArea,使其滚动到底部。然后还可以在其他一些输入字段上调用 focus(),以允许用户在该字段中进行输入。这就像魅力一样:

function myFunc() {
var txtArea = document.getElementById("myTextarea");
txtArea.value += "whatever"; // doesn't matter how it is updated
txtArea.focus();
var someOtherElem = document.getElementById("smallInputBox");
someOtherElem.focus();
}

在你的 HTML 中..。

<textarea id="logTextArea" style="width:600px;height:200px;"></textarea>

在你的 Javascript 中..。

<script language="javascript">


function loadLog(logValue) {
logTa = document.getElementById("logTextArea")
logTa.value = logValue;
scrollLogToBottom()
}


function scrollLogToBottom() {
logTa = document.getElementById("logTextArea")
logTa.scrollTop = logTa.scrollHeight;
}


loadLog("This is my really long text block from a file ... ")


</script>

我发现,在将新值加载到文本区域之后,需要将将 scrollHeight 设置为一个单独的函数的代码放入其中。

这对我来说很有效,也很直接(2022) ,所以我想分享:

function scrollToBottom (t) {
t.selectionStart = t.selectionEnd = t.value.length;
t.blur()
t.focus()
// t.blur() // uncomment if you don't want a final focus
}


scrolltoBottom(myTextarea)

技巧是将光标放在文本区域的末尾,快速取消焦点/重新对焦以更新视图。


If you don't want to mess with the focus, use this function :

const scrollToBottom = t=>t.scrollTop=t.scrollHeight;