gpt4 book ai didi

javascript - 如何防止textarea在其值发生变化时滚动到顶部?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:09:38 25 4
gpt4 key购买 nike

考虑以下示例:( 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);

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

关于javascript - 如何防止textarea在其值发生变化时滚动到顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7220997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com