【问题标题】:How do I determine scrollHeight?如何确定滚动高度?
【发布时间】:2011-09-11 22:48:05
【问题描述】:

如何确定使用 css overflow:auto 的除法的scrollHeight?

我试过了:

$('test').scrollHeight();
$('test').height(); but that just returns the size of the div not all the content

最终,我正在尝试创建一个聊天,并始终在屏幕上显示当前消息的滚动条。

所以我在想类似以下的事情:

var test = $('test').height();
$('test').scrollTop(test);

谢谢,

布莱恩

【问题讨论】:

  • 使用 scrollHeight() 有什么问题?
  • @BadrHari: jQuery 中没有scrollHeight() 函数。
  • 它是 $('test').get(0).scrollHeight();

标签: javascript jquery


【解决方案1】:

jQuery 中的正确方法是 -

  • $('#test').prop('scrollHeight') 或
  • $('#test')[0].scrollHeight 或
  • $('#test').get(0).scrollHeight

【讨论】:

  • +1 for $('#test')[0].scrollHeight,因为提问者已经在使用 jQuery。
  • 这应该是公认的答案,因为它回答了问题。
  • 这应该是公认的答案。请注意,prop 方法需要 jquery 版本 1.6 或更高版本。来自我的 +1
  • 请注意,这仅返回找到的“第一个”元素的 scrollHeight,如果当前有任何元素“隐​​藏”,即使其他元素的 scrollHeight 为正值,您也可能在此处得到零,FWIW :)跨度>
  • @rogerdpack 好点先生!虽然在这个例子中他使用了一个 ID 而不是一个类作为选择器,所以他应该没问题,但仍然很好。
【解决方案2】:

@987654321@ 是一个常规的 javascript 属性,所以你不需要 jQuery。

var test = document.getElementById("foo").scrollHeight;

【讨论】:

  • 谢谢!这对我有用: var height = document.getElementById("chatLog").scrollHeight - $('#chatLog').height(); $('#chatLog').scrollTop(height);
  • 浏览器支持怎么样?所有主要版本的浏览器都支持吗? IE8+?
  • @Cupidvogel 链接的 MDN 页面显示 IE8+
【解决方案3】:

你也可以使用:

$('#test').context.scrollHeight

【讨论】:

  • prop('scrollHeight') 有效,但 context.scrollHeight 无效:“消息:未捕获的类型错误:无法读取未定义的属性 'scrollHeight'”
  • 现在最好不要使用这种方法,它在 3.0.0 中被删除了。 api.jquery.com/context
猜你喜欢
  • 2020-01-05
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 2012-06-14
  • 2011-06-29
  • 2017-05-11
相关资源
最近更新 更多