开发者

Jquery: scroll page down 100px from where it currently is [duplicate]

This question already has answers here: ;Jquery: animate page down 100px from current screen posit开发者_高级运维ion (3 answers) Closed 9 years ago.

How do I animate the page down 100px from where it currently is?

my code doesn't work:

    $('html,body').animate({
        scrollTop: $(window).position().top + 100
    })

like this, but without it scrolling the page to a specific element, instead, scrolling 100px from the windows current position:

$('html, body').animate({
scrollTop: $("#scrollToHere").offset().top
}, 2000);


The scrollTop property tells you where the element is placed from the top. You have to use the window.scrollBy method and the window.scrollY property. Unfortunately you can't use animate on the window.scrollY property since it's read-only.

You should be able to use something like this:

function animateScrollBy (x, y, interval) {
    var xpos = 0,
    ypos = 0,
    updateScroll = function () {
        var moveX = xpos <= x ? 1 : 0,
            moveY = ypos <= y ? 1 : 0;

        window.scrollBy(moveX, moveY);
        xpos += 1;
        ypos += 1;
        if (moveX === 0 && moveY === 0) {
            clearInterval(scrollInterval);
        }

    },
    scrollInterval = null;

    scrollInterval = setInterval(updateScroll, interval||1)
}

animateScrollBy(0, 100);

The speed is relavant to the amout of pixels moved. I'll try it to update it later.


The scrollto plugin comes to mind:
http://flesler.blogspot.com/2007/10/jqueryscrollto.html
http://demos.flesler.com/jquery/scrollTo/

but maybe it's a bit overkill for that :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜