简体   繁体   中英

When my whole page has 'position: absolute', how do I check if I am at the top or not?

I have a main menu at the top of the website which when the user scrolls, changes and becomes more compact.

I was achieving that by checking scrolling events and whether we're at the top or not. This is the code that was working:

/*Defines how the 'main menu' will be displayed when we scroll down (if) and how it will fallback to original look when we're up again (else)*/
$(document).ready(function(){   
    if ($(window).width() > 480){                //not on mobile, then:
    $(window).bind('scroll', function () {
    if ($(window).scrollTop() > 0) {
        $('.visible-bar-container').css("position", "fixed");
        $("#white-logo").css("display", "none");
        //...etc

    } else {
        $('.visible-bar-container').css("position", "absolute");
        $("#spread-out-menu").css("display", "flex");
        //...etc
        }
    });
    }
});                                 

Mid project, the client decides that he wants the sections of the homepage to have a 'smooth scroll'. Long story short, I managed to do that after giving the whole homepage a CSS of position: absolute.

In case it matters, here is the whole CSS added to my homepage (which falls inside an element with id='main'):

#main {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: auto;
}

The problem is that now, the js code no longer works. (I believe that when the whole page has position absolute, checking for scrolling events no longer works-?). How then, can I check if the user has scrolled?

I might try checking whether user has moved past first section (through seeing if the div is visible in the viewport), but I would prefer the menu to become compact once we started moving down, not after the whole section has been moved past. So is there a way to check scrolling in this case?

I am the OP - so the answer was provided by Sim1-81 in the comments above. The trick was to change the third and fourth lines in the javascript:

...
 $("#main").bind('scroll', function () {
    if ($("#main").scrollTop() > 0) {
...

Where #main in my case is the id of the of page which I set to be 'position: absolute'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM