How to prevent textarea from scrolling to the top

2019-07-03 00:06发布

问题:

Consider the following example: (Live demo here)

HTML:

<textarea></textarea>
<div id="button">Click Here</div>

CSS:

textarea {
    height: 80px;
    width: 150px;
    background-color: #bbb;
    resize: none;
    border: none;
}
#button {
    width: 150px;
    background-color: #333;
    color: #eee;
    text-align: center;
}

JS:

$(function() {
    var textarea = $("textarea");

    textarea.val("Hello\nStack\nOverflow!\nThere\nAre\nLots\nOf\nGreat\nPeople\nHere");

    $("#button").click(function() {
        textarea.val(textarea.val() + "!");
    });

    textarea.scrollTop(9999).focus(); // Arbitrary big enough number to scroll to the bottom
});

When the #button is clicked, textarea value changes, and for some reason the scroll bar goes to the top (I checked this in Firefox, not sure about other browsers).

Why this is happening ?

How could I fix that ?

I found here one possible solution, but I wonder if there are other solutions.

回答1:

You can save the scrollTop offset, set the value, and reset the scrollTop to the old offset:

var $textarea = ...;
var top = $textarea.scrollTop();
$textarea.val('foo');
$textarea.scrollTop(top);

Try it here: http://jsfiddle.net/QGJeE/7/



回答2:

Another solution(harder to imply as there is no unique cross-browser-way):

Instead of changing the value of the textarea create a textRange of the textarea's content and modify the ranges text.