![](/img/trans.png)
[英]How do I stop a textarea from scrolling to the top whenever I change its value
[英]How to prevent textarea from scrolling to the top when its value changed?
請考慮以下示例:( 此處為現場演示 )
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中檢查了這一點,不確定其他瀏覽器)。
為什么會這樣?
我怎么能解決這個問題?
您可以保存scrollTop偏移量,設置值,並將scrollTop重置為舊偏移量:
var $textarea = ...;
var top = $textarea.scrollTop();
$textarea.val('foo');
$textarea.scrollTop(top);
在這里試試: http : //jsfiddle.net/QGJeE/7/
另一個解決方案(更難以暗示,因為沒有獨特的跨瀏覽器方式):
而不是更改textarea的值創建textarea的內容的textRange並修改范圍文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.