$(window).scrollTop() vs. $(document).scrollTop()

旧城冷巷雨未停 提交于 2019-11-26 06:55:50

问题


What\'s the difference between:

$(window).scrollTop()

and

$(document).scrollTop()

Thanks.


回答1:


They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().




回答2:


First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. Javascript is an object orientated language. You start with an object and apply methods to it's properties or the properties of it's object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is No difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.




回答3:


Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());



回答4:


I've just had some of the similar problems with scrollTop described here.

In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);

Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...



来源:https://stackoverflow.com/questions/5371139/window-scrolltop-vs-document-scrolltop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!