Function on window.scroll and get the vertical offset [duplicate]

为君一笑 提交于 2021-01-29 06:16:41

问题


window.scroll=function MyFunc(){
	var y = window.scrollTop();
	alert(y);
}
How to call a function when the window is scrolled and how to get the amount of pixels the window has been vertically scrolled. I want to play an animation when a desired value has been reached. Help.

回答1:


You can use window.onscroll without the use of jQuery. That was what you were missing on your code. It should be window.onscroll and to get the vertical scroll pixels use window.scrollY

window.onscroll = function (e) {
  console.log(window.scrollY);
};
html, body{
  height: 2000px;
}



回答2:


You need to wrap the window object in $() to use the scrollTop() function on it.

$(window).scroll(function MyFunc(e){
	var y = $(window).scrollTop();
	console.log(y);
});
html, body{
  height: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In Javascript, you can add an event listener for the scroll event on the window and use window.pageYOffset (for better cross-browser compatability) to get the amount of pixels scrolled vertically.

window.addEventListener("scroll", function MyFunc(e){
  var y = (window.pageYOffset !== undefined)
  ? window.pageYOffset
  : (document.documentElement || document.body.parentNode || document.body).scrollTop;//for cross-browser compatability
  console.log(y);
});
html, body{
  height: 2000px;
}


来源:https://stackoverflow.com/questions/51933055/function-on-window-scroll-and-get-the-vertical-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!