Why does .animate to scrollTop jump to 0 before animating?

青春壹個敷衍的年華 提交于 2019-12-11 01:58:14

问题


I am playing with Parallax scrolling like on that nike site. So I have been using scrollTop to determine the user's vertical position on the page and then I've been adjusting element's positions based on the changes to that value.

Here I round the scrollTop value and log it. I'll show the log later.

var distance = 60*(Math.round($(window).scrollTop()/60));
console.log(distance);

Then, on click, I call this function which scrolls to the scrollTop value that I've passed it.

function goTo(n){
    console.log('begin animating');
    $('html,body').animate({scrollTop: n},2000);
}

Here's the problem, the scroll top value jumps to 0 before animating.

So I'll be halfway down the page and it logs:

begin animating
0
6240
6180
6120
// etc...

The way I'm positioning stuff relies on the accuracy of the scrollTop value. So my question is:

How can I keep the scrollTop value from jumping to 0 before going through with the animation?

Let me know if theres any more info needed.
Heres the live version of the site: http://theblueeyeguy.com/moon/Illumination/

(click 'Next' then 'Prev' to break it)


回答1:


Probably because you're using a link with href="#".

Add return false; to your onclick attribute.

<a href="#" onClick="goTo(2160);return false;">< Prev | </a>


来源:https://stackoverflow.com/questions/8319051/why-does-animate-to-scrolltop-jump-to-0-before-animating

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