如何防止textarea的值更改时滚动到顶部? [英] How to prevent textarea from scrolling to the top when its value changed?

查看:232
本文介绍了如何防止textarea的值更改时滚动到顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的例子:(现场演示



HTML:

 < textarea>< / textarea> 
< div id =button>点击此处< / div>

CSS:

  textarea {
height:80px;
width:150px;
background-color:#bbb;
resize:none;
border:none;
}
#button {
width:150px;
背景颜色:#333;
color:#eee;
text-align:center;






$ b $ $ $($)$($)$($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (\\){$ b $(#button))。 b textarea.val(textarea.val()+!);
});

textarea.scrollTop(9999).focus(); //任意大的数字底部
});

单击 #button code> textarea 值的变化,由于某种原因滚动条到顶部(我在Firefox中检查过,不知道其他浏览器)

为什么会发生这种情况?



我该如何解决这个问题?



a href =https://stackoverflow.com/questions/3202791/how-do-i-stop-a-textarea-from-scrolling-to-the-top-whenever-i-change-its-value/3302664# 3302664这里一个可能的解决方案,但我不知道是否有其他的解决方案。

解决方案

scrollTop offset,设置该值,并将scrollTop重置为旧的偏移量:

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

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


Consider the following example: (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
});

When the #button is clicked, textarea value changes, and for some reason the scroll bar goes to the top (I checked this in Firefox, not sure about other browsers).

Why this is happening ?

How could I fix that ?

I found here one possible solution, but I wonder if there are other solutions.

解决方案

You can save the scrollTop offset, set the value, and reset the scrollTop to the old offset:

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

Try it here: http://jsfiddle.net/QGJeE/7/

这篇关于如何防止textarea的值更改时滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆