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

孤人 提交于 2019-12-11 17:17:19

问题


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

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4883391/jquery-scroll-page-down-100px-from-where-it-currently-is

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