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

标签 javascript jquery firefox scroll textarea

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

相关文章:

javascript - 如何将秒转换为 HH :mm:ss in moment. js

javascript - Angular 加载完成后运行 jQuery

javascript - HTML/JS github pages 元素在使用 firefox 运行时不加载图像或声音

javascript - Firefox 中断词的解决方法

javascript - 如何获得删除 Google 表格中的行的权限?

php - 使用池的在线聊天

jquery - Firefox 和 Chrome CSS 绝对定位问题

javascript - 如果安装了插件,如何检查 Firefox 和 Chrome

javascript - 如何在嵌套 promise 中传播resolve()?

javascript - Jquery 循环和递增