[英]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.scrollTop
或document.body.scrollTop
或textarea
, 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 在document.body.scrollTop与document.documentElement.scrollTop上找到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.