$(window).scroll 在原生 JavaScript 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14389687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$(window).scroll in vanilla JavaScript
提问by Neo
What's the equivalent of the following in plain JS?
$(window).scroll(function() { });I'm also looking to animate scroll, e.g.:
$('html, body').animate({scrollTop:1750}, 'slow');
普通 JS 中的以下等效项是什么?
$(window).scroll(function() { });我也在寻找动画滚动,例如:
$('html, body').animate({scrollTop:1750}, 'slow');
Should I be using requestAnimationFrame?
我应该使用requestAnimationFrame吗?
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
Are there any examples that trigger an animation once on click and not continuous renders?
是否有任何示例在单击时触发动画而不是连续渲染?
回答by Jonathan F
Question 1
问题 1
window.onscroll = function() {
console.log('scrolling');
};
or if your targeted browsers supportaddEventListener:
或者如果您的目标浏览器支持addEventListener:
window.addEventListener('scroll', function() {
console.log('scrolling');
});
Question 2
问题2
In my opinion, if you're just scrolling from one section to a another section of your page, and not having some sort of constantly running scrolling movement, you're fine doing this without using requestAnimationFrame.
在我看来,如果您只是从页面的一个部分滚动到另一部分,并且没有某种不断运行的滚动运动,那么不使用 requestAnimationFrame 就可以做到这一点。
You can find good implementations of scrolling to a particular part of the window in pure javascript, I suggest checking out their source(or even using them).
您可以在纯 javascript 中找到滚动到窗口特定部分的良好实现,我建议查看它们的源代码(甚至使用它们)。

