How to prevent textarea from scrolling to the top when its value changed?

对着背影说爱祢 提交于 2019-12-23 17:47:52

问题


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.



来源:https://stackoverflow.com/questions/7220997/how-to-prevent-textarea-from-scrolling-to-the-top-when-its-value-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!