Javascript $(window).scrollTop() 与 $(document).scrollTop()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5371139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$(window).scrollTop() vs. $(document).scrollTop()
提问by frenchie
What's the difference between:
有什么区别:
$(window).scrollTop()
and
和
$(document).scrollTop()
Thanks.
谢谢。
采纳答案by Bodman
They are both going to have the same effect.
它们都会产生相同的效果。
However, as pointed out in the comments: $(window).scrollTop()
is supported by more web browsersthan $('html').scrollTop()
.
然而,由于在评论中指出:$(window).scrollTop()
由多个Web浏览器支持比$('html').scrollTop()
。
回答by Hussein
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 its properties or the properties of its 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
。该window
对象是顶级客户端对象。window
物体上方没有任何东西。JavaScript 是一种面向对象的语言。您从一个对象开始,然后将方法应用于其属性或其对象组的属性。例如,document
对象是对象的window
对象。要更改document
的背景颜色,您需要设置document
的bgcolor
属性。
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.
要回答您的问题,window
和之间的最终结果没有区别document
scrollTop
。两者都会给出相同的输出。
Check working example at http://jsfiddle.net/7VRvj/6/
在http://jsfiddle.net/7VRvj/6/检查工作示例
In general use document
mainly to register events and use window
to do things like scroll
, scrollTop
, and resize
.
在一般的使用document
主要是为了注册的事件,使用window
到做这样的事情scroll
,scrollTop
和resize
。
回答by amachree tamunoemi
Cross browser way of doing this is
这样做的跨浏览器方式是
var top = ($(window).scrollTop() || $("body").scrollTop());
回答by Tapiochre
I've just had some of the similar problems with scrollTop
described here.
我刚刚遇到了一些与scrollTop
此处描述的类似问题。
In the end I got around this on Firefoxand IEby using the selector $('*').scrollTop(0);
最后,我通过使用选择器在Firefox和IE上解决了这个问题$('*').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...
如果您有不想影响的元素,则不完美,但它绕过了文档、正文、HTML 和窗口的差异。如果有帮助...