如何防止textarea在值改变时滚动到顶部?
请考虑以下示例:( 此处为现场演示 )
HTML:
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中检查过这个,不确定其他浏览器)。
为什么会这样?
我怎么能解决这个问题?
我在这里找到了一个可能的解决方案,但我想知道是否有其他解决方案。
您可以保存scrollTop偏移量,设置值,并将scrollTop重置为旧偏移量:
var $textarea = ...; var top = $textarea.scrollTop(); $textarea.val('foo'); $textarea.scrollTop(top);
在这里试试: http : //jsfiddle.net/QGJeE/7/
另一个解决方案(更难以暗示,因为没有独特的跨浏览器方式):
而不是更改textarea的值创建textarea的内容的textRange并修改范围文本。