在JQuery中测试元素是否在屏幕顶部 [英] Test in JQuery if an element is at the top of screen

查看:79
本文介绍了在JQuery中测试元素是否在屏幕顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆