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

后端 未结 5 1440
予麋鹿
予麋鹿 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条回答
  •  天涯浪人
    2020-12-23 12:05

    Not so much an answer, but could be helpful to someone else. Using the accepted answer above and also referencing the 'Learning from Twitter' link (thank you @Joseph Sibler) I came up with the following.

    I am using a Twitter Bootstrap Navbar for my primary navigation. It has an ID of megamenu.

    I also have a 'login' button on my page that when clicked, slides the navbar and all contents below it down to reveal the login form. So what? Well, now the position of my navbar has changed and if I don't update that position, when I scroll the navbar will fly up to the top of the browser - even though it's not really at the top.

    I came up with this to update the navbar position so if a user clicks 'login' and then scrolls, the navbar will correctly fix itself to the top.

    logincollapse is my container div that holds the login form and other hidden content until the login button is clicked.

    I'm sure there is room for improvement - so please correct me, I'll update accordingly.

    jquery

    var did_scroll = false,
        $window = $(window),
        megamenu_distance = $('#megamenu').offset().top; // The default position of the navbar
    
    $('#logincollapse').slideToggle(300, 'easeInOutQuint', function () {
        megamenu_distance = $('#megamenu').position().top; // Updated position of the navbar
        ....
    });
    
    $window.scroll(function (event) {
        did_scroll = true;
    });
    
    setInterval(function () {
        if (did_scroll)
        {
            did_scroll = false;
    
            if ($window.scrollTop() >= megamenu_distance)
            {
                $('#megamenu').addClass('navbar-fixed-top');
            }
            else
            {
                $('#megamenu').removeClass('navbar-fixed-top');
            }
        }
    }, 250);
    

提交回复
热议问题