How do I set textarea scroll bar to bottom as a default?

后端 未结 4 1171
执念已碎
执念已碎 2020-12-02 08:32

I have a textarea that is being dynamically reloaded as user input is being sent in. It refreshes itself every couple seconds. When the amount of text in this textarea excee

相关标签:
4条回答
  • 2020-12-02 08:42

    I had the same problem and found out that there is no attribute that can be set initially to get the right scrolling behaviour. However, once the text is updated in the textArea, immediately after in the same function you can set the focus() to textArea to make it scroll to bottom. You can then call focus() on some other input field as well to allow user to input in that field. This works like charm:

    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();
    }
    
    0 讨论(0)
  • 2020-12-02 08:47

    pretty simple, in vanilla javascript:

    var textarea = document.getElementById('textarea_id');
    textarea.scrollTop = textarea.scrollHeight;
    
    0 讨论(0)
  • 2020-12-02 08:48

    You can use this with jQuery

    $(document).ready(function(){
        var $textarea = $('#textarea_id');
        $textarea.scrollTop($textarea[0].scrollHeight);
    });
    
    0 讨论(0)
  • 2020-12-02 08:56

    In your HTML ...

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

    In your 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>
    

    I have found that you need to put the code to set the scrollHeight into a separate function after loading the new value into the text area.

    0 讨论(0)
提交回复
热议问题