简体   繁体   中英

ScrollY/ScrollTop doesn't work when height of html and body is 100%

I'm using height: 100% and overflow: auto on html / body to fix a scroll bug on Chrome. However ScrollY / ScrollTop always return 0 now. Is there any way to check scroll position in this case?

HTML:

<html>
    <body>
        <div class="wrapper">
            <div class="top-nav">
            <div class="scroll-wrapper">
        </div>
    <body>
</html>

CSS:

html {
    height: 100%;
    overflow: auto;

    body {
        height: 100%;
        overflow: auto;

        .wrapper {
            .top-nav {
                z-index: 999;
                position: fixed;
                top: 0;
            }
            .scroll-wrapper {
                padding-top: 45px;
            }
        }
    }
}

JS:

    // Add style to top-nav when scrolling down

    $('.wrapper').scroll(function () {
        if (window.scrollY > 0)                        //always 0
        if ($('.wrapper')[0].scrollTop > 0)   
        if ($('.scroll-wrapper')[0].scrollTop > 0)
    }

EDIT

It appears your issue actually steams from both html and html body having overflow: scroll .

Try removing one of those CSS rules and see if your initial problem is still solved.

html {
    height: 100%;
    /* overflow: auto; */

    body {
        height: 100%;
        overflow: auto;

       /* ... */

    }
}

You also need to change your javascript to check for document scrolling and not the wrapper.

$(document).scroll(function () {
    console.log(document.body.scrollTop)
    if (document.body.scrollTop > 0) {
        // Perform Action
    }
})

Hope that solves your issue.

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