Javascript 使用 jquery 获取滚动位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14886038/
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
Get scroll position using jquery
提问by centree
Strange request, but I need to get the current browser scroll position as a variable. What js or jquery function should I use? I need it to figure out what elements to display on the side. I've found a few things online but nothing that works for my div, just the full page.
奇怪的请求,但我需要获取当前浏览器滚动位置作为变量。我应该使用什么 js 或 jquery 函数?我需要它来确定要在侧面显示哪些元素。我在网上找到了一些东西,但对我的 div 没有任何作用,只有整页。
回答by arturmoroz
cross browser variant
跨浏览器变体
$(document).scrollTop();
回答by adeneo
Older IE and Firefox browsers attach the scrollbar to the documentElement, or what would be the <html>tag in HTML.
较旧的 IE 和 Firefox 浏览器将滚动条附加到documentElement或<html>HTML 中的标签。
All other browsers attach the scrollbar to document.body, or what would be the <body>tag in HTML.
所有其他浏览器都将滚动条附加到document.body,或者<body>HTML 中的标签。
The correct solution would be to check which one to use, depending on browser
正确的解决方案是检查使用哪个,具体取决于浏览器
var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s = $(doc).scrollTop();
jQuery does make this a little easier, when passing in either windowor documentjQuery's scrollTopdoes a similar check and figures it out, so either of these should work cross-browser
jQuery 确实让这变得更容易一些,当传入其中一个window或documentjQuery 时scrollTop会进行类似的检查并计算出来,所以这些都应该跨浏览器工作
var s = $(document).scrollTop();
or
或者
var s = $(window).scrollTop();
Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
描述:获取匹配元素集合中第一个元素的滚动条当前垂直位置或为每个匹配元素设置滚动条的垂直位置。
...nothing that works for my div, just the full page
...没有什么适合我的 div,只有整页
If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount
如果是用于 DIV,则必须以附加滚动条的元素为目标,以获取滚动量
$('div').scrollTop();
If you need to get the elements distance from the top of the document, you can also do
如果您需要从文档顶部获取元素距离,您也可以这样做
$('div').offset().top
回答by Daryl Ginn
I believe the best method with jQuery is using .scrollTop():
我相信 jQuery 的最佳方法是使用.scrollTop():
var pos = $('body').scrollTop();
回答by Umar Farooq Khawaja
Use scrollTop()to get or set the scroll position.
使用scrollTop()获取或设置滚动位置。

