开发者

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

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 ch开发者_开发技巧anges, 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.


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/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜