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

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

问题描述

我有一个 div,它使用 overflow:auto 将内容保留在 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;

然而,它给了我不一致的结果.有时有效,有时无效,如果用户手动调整 div 大小或移动滚动条,它就完全停止工作.

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 值.

...which will set the scroll offset to the last clientHeight worth of content.

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

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