Test in JQuery if an element is at the top of screen

后端 未结 5 1453
予麋鹿
予麋鹿 2020-12-23 11:42

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

5条回答
  •  猫巷女王i
    2020-12-23 12:01

    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.

提交回复
热议问题