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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:54:52  来源:igfitidea点击:

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

javascriptjquerywindowdocumentscrolltop

提问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 windowand document. The windowobject is a top level client side object. There is nothing above the windowobject. 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 documentobject is an object of the windowobject. To change the document's background color, you'd set the document's bgcolorproperty.

首先,你需要明白之间的差别windowdocument。该window对象是顶级客户端对象。window物体上方没有任何东西。JavaScript 是一种面向对象的语言。您从一个对象开始,然后将方法应用于其属性或其对象组的属性。例如,document对象是对象的window对象。要更改document的背景颜色,您需要设置documentbgcolor属性。

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between windowand documentscrollTop. Both will give the same output.

要回答您的问题,window和之间的最终结果没有区别documentscrollTop。两者都会给出相同的输出。

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

http://jsfiddle.net/7VRvj/6/检查工作示例

In general use documentmainly to register events and use windowto do things like scroll, scrollTop, and resize.

在一般的使用document主要是为了注册的事件,使用window到做这样的事情scrollscrollTopresize

回答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 scrollTopdescribed here.

我刚刚遇到了一些与scrollTop此处描述的类似问题。

In the end I got around this on Firefoxand IEby using the selector $('*').scrollTop(0);

最后,我通过使用选择器在FirefoxIE上解决了这个问题$('*').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 和窗口的差异。如果有帮助...