简体   繁体   中英

window.scrollTop is undfined

why would window.scrollTop be undefined?

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

The Element.scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically.

An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0.

jQuery(window).on('scroll', function() {
        if(window.scrollTop > 0) {
            console.log('of the top')
            console.log('scroll top value is: ' + window.scrollTop)
        } else {
            console.log('the top')
            console.log('scroll top value is: ' + window.scrollTop)
        }
    })

All I'm getting in my console log is:

scroll top value is: undefined

and I'm always getting an evaluation of in the if else:

of the top

even if I'm scrolled to the top of the page.

Why would window.scrollTop be undefined?

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop does window not count as an element?

You need to use the jQuery $ identifier as well as the parenthesis () for.scrollTop() in order to get the position

Here's the executable code:

<script>
jQuery(window).on('scroll', function() {
        if($(window).scrollTop() > 0) {
            console.log('of the top')
            console.log('scroll top value is: ' + $(window).scrollTop())
        } else {
            console.log('the top')
            console.log('scroll top value is: ' + $(window).scrollTop())
        }
    })
</script>
<script> jQuery(window).on('scroll', function() { if($(window).scrollTop() > 0) { console.log('of the top') console.log('scroll top value is: ' + $(window).scrollTop()) } else { console.log('the top') console.log('scroll top value is: ' + $(window).scrollTop()) } }) </script>

YESSINE's code is correct. but can make it simple

<script>
jQuery(window).on('scroll', function() {
        var window = $(window);
        if(window.scrollTop() > 0) {                
            console.log('of the top')
            console.log('scroll top value is: ' + window.scrollTop())
        } else {
            console.log('the top')
            console.log('scroll top value is: ' + window.scrollTop())
        }
    })
</script>

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