考虑以下示例:( 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
});
当 #button
被点击时,textarea
的值发生变化,并且由于某种原因滚动条会回到顶部(我在 Firefox 中检查过这个,不确定其他浏览器)。
为什么会这样?
我该如何解决?
我找到了 here一种可能的解决方案,但我想知道是否还有其他解决方案。
最佳答案
您可以保存 scrollTop 偏移量,设置值,并将 scrollTop 重置为旧偏移量:
var $textarea = ...;
var top = $textarea.scrollTop();
$textarea.val('foo');
$textarea.scrollTop(top);
关于javascript - 如何防止textarea在其值发生变化时滚动到顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7220997/