在JQuery中测试元素是否在屏幕顶部 [英] Test in JQuery if an element is at the top of screen
问题描述
我有一个div
,它距浏览器窗口顶部约100像素.当用户向下滚动时,我希望div
停留在直到的位置,直到到达屏幕顶部.然后,我将使用JQuery更改一些CSS,以将位置更改为固定,并将margin-top更改为0.如何在JQuery中测试此div
是否在屏幕顶部?
var distance = $('div').offset().top,
$window = $(window);
$window.scroll(function() {
if ( $window.scrollTop() >= distance ) {
// Your div has reached the top
}
});
PS .为获得更好的性能,您可能应该限制滚动事件处理程序.
请查看John Resig的文章: 从Twitter学习 . /p>
I have a div
that is positioned about 100px from the top of the browser window. When the user scrolls down, I want the div
to stay where it is until it reaches the top of the screen. Then, I'll change some CSS with JQuery to make the position to change to fixed and the margin-top to 0. How can I test in JQuery if this div
is at the top of the screen?
var distance = $('div').offset().top,
$window = $(window);
$window.scroll(function() {
if ( $window.scrollTop() >= distance ) {
// Your div has reached the top
}
});
P.S. For better performance, you should probably throttle the scroll event handler.
Check out John Resig's article: Learning from Twitter.
这篇关于在JQuery中测试元素是否在屏幕顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!