【发布时间】:2011-03-25 08:13:06
【问题描述】:
如何获取文档的滚动位置值?
【问题讨论】:
如何获取文档的滚动位置值?
【问题讨论】:
你可以试试这个例子,这段代码把滚动条放在所有DIV标签的底部
记住:jQuery 可以接受一个函数而不是值作为参数。 “this”是jQuery处理的对象,函数返回当前DIV“this”的scrollHeight属性并对文档中的所有DIV进行处理。
$("div").scrollTop(function(){return this.scrollHeight})
【讨论】:
试试这个:
var scrollHeight = $(scrollable)[0] == document ? document.body.scrollHeight : $(scrollable)[0].scrollHeight;
【讨论】:
它使用 HTML DOM 元素,但不使用 jQuery 选择器。 它可以像这样使用:
var height = document.body.scrollHeight;
【讨论】:
以下是使用 jQuery 选择器获取元素的scrollHeight 的方法:
$(selector)[0].scrollHeight
如果selector是元素的id(例如elemId),保证数组的0索引项就是你要选择的元素,scrollHeight是正确的。
【讨论】:
为了获得窗口滚动条滚动区域的实际可滚动高度,我使用了$('body').prop('scrollHeight')。这似乎是最简单的工作解决方案,但我没有广泛检查兼容性。 Emanuele Del Grande 指出另一个解决方案,这可能不适用于 8 以下的 IE。
大多数其他解决方案都适用于可滚动元素,但这适用于整个窗口。值得注意的是,对于 Ankit 的解决方案,我遇到了与 Michael 相同的问题,即 $(document).prop('scrollHeight') 正在返回 undefined。
【讨论】:
document.getElementById("elementID").scrollHeight
$("elementID").scrollHeight
【讨论】:
如果您使用的是 Jquery 1.6 或更高版本,请使用 prop 访问该值。
$(document).prop('scrollHeight')
以前的版本用于从 attr 获取值,但不是在 1.6 之后。
【讨论】:
这样的事情应该可以解决你的问题:
$.getDocHeight = function(){
var D = document;
return Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
};
alert( $.getDocHeight() );
Ps:每次需要时调用该函数,警报是为了测试目的..
【讨论】:
$(document).height() //returns window height
$(document).scrollTop() //returns scroll position from top of document
【讨论】:
scrollHeight 的问题。