在 javascript / jQuery 中检测滚动元素的偏移量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6460116/
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
Detecting offset of an element on scroll in javascript / jQuery
提问by jeffreynolte
I am looking looking to calculate the distance between an element and the top of the document window. On scroll I am able to get the initial value but it does not change. How can I find this value and what the number has changed to on scroll?
我正在寻找计算元素和文档窗口顶部之间的距离。在滚动时,我可以获得初始值,但它不会改变。我怎样才能找到这个值,以及滚动时数字变成了什么?
JS:
JS:
$(function() {
$(window).scroll(function() {
var h1 = $("h1");
console.log(h1.offset().top)
});
});
HTML:
HTML:
<div id="cover">
<h1>hello sir</h1>
</div>
回答by MidnightLightning
Compare the offset of the <h1>
element to how far down the page the user has scrolled. The $(window).scrollTop()
function will get you the amount the user has scrolled down so:
将<h1>
元素的偏移量与用户滚动到页面下方的距离进行比较。该$(window).scrollTop()
函数将为您提供用户向下滚动的数量,因此:
$(window).scroll(function() {
var $h1 = $("h1");
var window_offset = $h1.offset().top - $(window).scrollTop();
});
回答by Noyo
If you hate arithmetic (and extra function calls), this should do the trick:
如果你讨厌算术(和额外的函数调用),这应该可以解决问题:
$(function() {
var h1 = document.getElementsByTagName("h1")[0];
$(window).scroll(function() {
console.log(h1.getBoundingClientRect().top);
});
});
This is exactly what getBoundingClientRect()was made for.
回答by Aleks G
You can use this function to get the scroll offset of the window:
您可以使用此函数来获取窗口的滚动偏移量:
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}
Then you can use the offsets in your function to determine the real position of your element:
然后您可以使用函数中的偏移量来确定元素的实际位置:
$(function() {
$(window).scroll(function() {
var h1 = $("h1");
var offs = getScrollXY();
console.log(h1.offset().top - offs[1]);
});
});
Theoretically, this should work in all browsers, but, frankly, I didn't do too much testing.
理论上,这应该适用于所有浏览器,但坦率地说,我没有做太多测试。