简体   繁体   English

使用 jquery 获取滚动位置

[英]Get scroll position using jquery

Strange request, but I need to get the current browser scroll position as a variable.奇怪的请求,但我需要获取当前浏览器滚动位置作为变量。 What js or jquery function should I use?我应该使用什么 js 或 jquery 函数? 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.我在网上找到了一些东西,但对我的 div 没有任何作用,只有整页。

跨浏览器变体

$(document).scrollTop();

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 ,或者 HTML 中的<body>标签。

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 window or document jQuery's scrollTop does a similar check and figures it out, so either of these should work cross-browser jQuery 确实让这更容易一些,当传入windowdocument jQuery 的scrollTop会做类似的检查并计算出来,所以这两个都应该跨浏览器工作

var s = $(document).scrollTop();

or要么

var s = $(window).scrollTop();

jQuery scrollTop() docs jQuery 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

我相信 jQuery 最好的方法是使用.scrollTop()

var pos = $('body').scrollTop();

使用scrollTop()获取或设置滚动位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM