如何防止textarea在值改变时滚动到顶部?

Mis*_*hko 3 javascript firefox jquery scroll textarea

请考虑以下示例:( 此处为现场演示)

HTML:

<textarea></textarea>
<div id="button">Click Here</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

textarea {
    height: 80px;
    width: 150px;
    background-color: #bbb;
    resize: none;
    border: none;
}
#button {
    width: 150px;
    background-color: #333;
    color: #eee;
    text-align: center;
}
Run Code Online (Sandbox Code Playgroud)

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
});
Run Code Online (Sandbox Code Playgroud)

#button被点击时,textarea值的变化,以及由于某种原因滚动条去顶(我在Firefox中选中此,不知道其他浏览器).

为什么会这样?

我怎么能解决这个问题?

我在这里找到一个可能的解决方案,但我想知道是否有其他解决方案.

Arn*_*anc 9

您可以保存scrollTop偏移量,设置值,并将scrollTop重置为旧偏移量:

var $textarea = ...;
var top = $textarea.scrollTop();
$textarea.val('foo');
$textarea.scrollTop(top);
Run Code Online (Sandbox Code Playgroud)

在这里试试:http://jsfiddle.net/QGJeE/7/