简体   繁体   中英

scrollTop not working on window scroll in javascript

I am trying to attached onscroll function to window. But when I use scrollTop to get the scroll position it is giving me undefined. Does scrollTop can be use with document element only ?

window.onscroll=function(){
  console.log(this.scrollTop)
}

Working code

window.onscroll=function(){
  console.log(this.scrollY)
}

Yes, scrollTop can only be used on scroll-able elements, like document.documentElement.scrollTop or document.body.scrollTop or a textarea , a div , ...

All-browsers-compatible code

window.onscroll=function(){
  console.log((document.documentElement || document.body.parentNode || document.body).scrollTop)
}

Found on document.body.scrollTop vs document.documentElement.scrollTop

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