javascript 动画窗口滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4949009/
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
Animating window scrolling
提问by D.C.
Hi I am using the following method to programmatically scroll a web document:
嗨,我正在使用以下方法以编程方式滚动 Web 文档:
window.scrollBy(0, delta)
The current implementation of scrollBy just jumps the document to the new position. Is there a way of animating this? I am using webkit specifically, and jQuery (or any other javascript framework) is not an option.
scrollBy 的当前实现只是将文档跳转到新位置。有没有办法对此进行动画处理?我专门使用 webkit,并且 jQuery(或任何其他 javascript 框架)不是一个选项。
Thanks for any help in advance.
提前感谢您的任何帮助。
回答by jAndy
You can just animate it by invoking an interval:
您可以通过调用间隔来为其设置动画:
setInterval(function() {
window.scrollBy(0, 5);
}, 13);
This of course would do it over and over, so you need to put in a conditional check, when to cancel the interval. Could look like:
这当然会一遍又一遍地执行,因此您需要进行条件检查,何时取消间隔。可能看起来像:
var timerID = setInterval(function() {
window.scrollBy(0, 5);
if( window.pageYOffset >= 500 )
clearInterval(timerID);
}, 13);
回答by EmmaGamma
Every time this function is called, it will jump the number of pixels in window.scrollBy (0,5), regardless of where the pageYOffset is. For instance, if pageYOffset is 300px, it will jump to 305px.
每次调用这个函数都会跳转window.scrollBy(0,5)中的像素数,不管pageYOffset在哪里。例如,如果 pageYOffset 为 300px,它将跳转到 305px。
but this problem can be solved by moving the if and adding an else
like so:
但是这个问题可以通过移动 if 并添加 else 来解决,
如下所示:
var timerID = setInterval(function() {
if( window.pageYOffset <= 500 )
window.scrollBy(0, 5);
else
clearInterval(timerID);
}, 1);

