How do I get the scroll position of a document?

2019-01-21 06:17发布

How to get the scroll position value of a document?

标签: jquery scroll
9条回答
手持菜刀,她持情操
2楼-- · 2019-01-21 06:39

You can try this for example, this code put the scrollbar at the bottom for all DIV tags

Remember: jQuery can accept a function instead the value as argument. "this" is the object treated by jQuery, the function returns the scrollHeight property of the current DIV "this" and do it for all DIV in the document.

$("div").scrollTop(function(){return this.scrollHeight})
查看更多
祖国的老花朵
3楼-- · 2019-01-21 06:41
document.getElementById("elementID").scrollHeight

$("elementID").scrollHeight
查看更多
forever°为你锁心
4楼-- · 2019-01-21 06:49

It uses HTML DOM Elements, but not jQuery selector. It can be used like:

var height = document.body.scrollHeight;
查看更多
戒情不戒烟
5楼-- · 2019-01-21 06:53

Here's how to get the scrollHeight of an element obtained using a jQuery selector:

$(selector)[0].scrollHeight

If selector is the id of the element (e.g. elemId), it is guaranteed that the 0-indexed item of the array will be the element you wish to select, and scrollHeight will be correct.

查看更多
爷的心禁止访问
6楼-- · 2019-01-21 06:53

To get the actual scrollable height of the areas scrolled by the window scrollbar, I used $('body').prop('scrollHeight'). This seems to be the simplest working solution, but I haven't checked extensively for compatibility. Emanuele Del Grande notes on another solution that this probably won't work for IE below 8.

Most of the other solutions work fine for scrollable elements, but this works for the whole window. Notably, I had the same issue as Michael for Ankit's solution, namely, that $(document).prop('scrollHeight') is returning undefined.

查看更多
Evening l夕情丶
7楼-- · 2019-01-21 06:54

Something like this should solve your problem:

$.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: Call that function every time you need it, the alert is for testing purposes..

查看更多
登录 后发表回答