最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Animating window scrolling - Stack Overflow

programmeradmin2浏览0评论

Hi I am using the following method to programmatically scroll a web document:

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.

Thanks for any help in advance.

Hi I am using the following method to programmatically scroll a web document:

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.

Thanks for any help in advance.

Share Improve this question asked Feb 9, 2011 at 18:36 D.C.D.C. 15.6k19 gold badges77 silver badges103 bronze badges 2
  • Whatever your reasons are for reinventing the wheel, you can still look at how the established frameworks implement smooth animations, and learn from that, no? – Thomas Commented Feb 9, 2011 at 18:41
  • 1 @Thomas: Since Webkit offers CSS animations with easing, it is not implausible to think that a similar native mechanism might be available for scrolling (which is not the case AFAIK) – user123444555621 Commented Feb 9, 2011 at 19:07
Add a ment  | 

2 Answers 2

Reset to default 13

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);

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.

but this problem can be solved by moving the if and adding an else
like so:

var timerID = setInterval(function() {
    if( window.pageYOffset <= 500 )
        window.scrollBy(0, 5);

    else
        clearInterval(timerID);
}, 1);
发布评论

评论列表(0)

  1. 暂无评论