【问题标题】:How to prevent textarea from scrolling to the top when its value changed?如何防止 textarea 在其值更改时滚动到顶部?
【发布时间】:2011-08-28 12:34:06
【问题描述】:

考虑以下示例:(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 一种可能的解决方案,但我想知道是否还有其他解决方案。

【问题讨论】:

  • 请注意,Chrome 不会发生这种情况。

标签: javascript jquery firefox scroll textarea


【解决方案1】:

您可以保存scrollTop偏移,设置值,并将scrollTop重置为旧偏移:

var $textarea = ...;
var top = $textarea.scrollTop();
$textarea.val('foo');
$textarea.scrollTop(top);

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

【讨论】:

    【解决方案2】:

    另一种解决方案(更难暗示,因为没有唯一的跨浏览器方式):

    不要更改 textarea 的值,而是创建 textarea 内容的 textRange 并修改范围文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2022-01-08
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多