简体   繁体   English

scrollTop在javascript中的窗口滚动上不起作用

[英]scrollTop not working on window scroll in javascript

I am trying to attached onscroll function to window. 我正在尝试将onscroll函数附加到窗口。 But when I use scrollTop to get the scroll position it is giving me undefined. 但是,当我使用scrollTop获取滚动位置时,它给了我未定义的信息。 Does scrollTop can be use with document element only ? scrollTop是否只能与文档元素一起使用?

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 , ... 是的, scrollTop只能用于可滚动元素,例如document.documentElement.scrollTopdocument.body.scrollToptextareadiv ,...

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 document.body.scrollTop与document.documentElement.scrollTop上找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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