滚动溢出的DIV使用JavaScript [英] Scrolling Overflowed DIVs with JavaScript

查看:96
本文介绍了滚动溢出的DIV使用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用溢出一个div:自动保持内容的DIV中,因为它被调整大小和页面各处拖动。我使用一些Ajax从服务器获取文本行,然后将它们添加到div的结尾,所以内容越来越向下。每当出现这种情况,我想用JS滚动div来的底部,所以最近添加的内容是可见的,类似的方式聊天室或命令行控制台会的工作。

I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.

到目前为止,我一直在使用这个片段来做到这一点(我也使用jQuery,因此$()函数):

So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):

$("#thediv").scrollTop = $("#thediv").scrollHeight;

但它已经给我不一致的结果。有时工作,有时没有,这完全停止工作,如果用户重新调整过的股利或手动移动滚动条。

However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.

目标浏览器是Firefox 3,和它被部署在受控环境所以它不需要在IE在所有工作

The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.

任何想法的家伙?这一次的让我难住了。谢谢!

Any ideas guys? This one's got me stumped. Thanks!

推荐答案

scrollHeight属性应该是内容的总高度。 scrollTop的指定像素偏移,这些内容将在该元素的客户区的顶部显示。

scrollHeight should be the total height of content. scrollTop specifies the pixel offset into that content to be displayed at the top of the element's client area.

所以,你真的想(仍然使用jQuery):

So you really want (still using jQuery):

$("#thediv").each( function() 
{
   // certain browsers have a bug such that scrollHeight is too small
   // when content does not fill the client area of the element
   var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
   this.scrollTop = scrollHeight - this.clientHeight;
});

...这将设置滚动偏移的内容最后 clientHeight 的价值。

这篇关于滚动溢出的DIV使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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