Dynamically Scrolling a Textarea

2019-01-07 19:35发布

I have a textarea html element on my page that gets reloaded via ajax. The whole textarea is returned each time not just its content, and the content grows over time. Along with the textarea i return the following piece of javascript:

<script type="text/javascript" >

var textArea = document.getElementById('outputTextResultsArea');
textArea.scrollTop = textArea.scrollHeight;
</script>

In firefox 3.0.7 this places the scroll bar at the bottom of the textArea, allowing me to see the latest of the output. However in IE 7 i see different behaviour. The scrollbar moves down with the content as intended, but once the content is greater then the textarea height the scroll bar no longer moves down. It seems as if IE is remembering the original scroll height of the element, not the new height.

I am using the xhtml transitional doctype if that helps. Also if this can be achieved with jQuery that would be fine as I have access to that.

Thanks in advance

Neil

4条回答
聊天终结者
2楼-- · 2019-01-07 20:15

Instead of using the timeout, call that function on every AJAX response - provided you can tweak it.

That would free your browser from unnecessary timeouts.

查看更多
小情绪 Triste *
3楼-- · 2019-01-07 20:19

I ended up using this for Internet Explorer:

textArea.createTextRange().scrollIntoView(false);

and this for other browsers:

textArea.scrollTop = textArea.scrollHeight;
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-07 20:20

As a quick hack you can just do this:

textArea.scrollTop = 99999;

Another option is to try it in a timer:

setTimeout(function()
{
    var textArea = document.getElementById('outputTextResultsArea');
    textArea.scrollTop = textArea.scrollHeight;
}, 10);
查看更多
做自己的国王
5楼-- · 2019-01-07 20:26

Using jQuery, $("textarea").scrollHeight(99999) works great on Firefox and Chrome but not on IE. It appears to set it to the max number of lines in the textarea, whereas scrollHeight is supposed to be the number of pixels. (Awesome show great job IE). This appears to work though:

      $("textarea").scrollTop(99999)
      $("textarea").scrollTop($("textarea").scrollTop()*12)

I think this assumes a 12px font-height. I would love to find a more robust/straightforward way to do this.

查看更多
登录 后发表回答