JQuery scrollTop function goes to correct position but then jumps back to top of page

半世苍凉 提交于 2021-02-18 12:27:09

问题


I used the JQuery function scrollTop on a list of contact numbers in a click function for each letter. It scrolls to where it is supposed to but then scrolls back to the top immediately.

Here is a sample of the function in the code:

$('.a').click(function(){
     $('html, body').animate({scrollTop:$('#A').position().top}, 'slow');
});

Here is the JSFiddle I made for it: http://jsfiddle.net/CR47/MdtSE/


回答1:


If you're adding this to an anchor tag, you normally need to add a preventDefault() or return false; to cancel the navigation event.

So:

$('.a').on('click', function(e){
    e.preventDefault();
    $('html, body').animate({scrollTop:$('#A').position().top}, 'slow');
});

or

$('.a').on('click', function(e){
    $('html, body').animate({scrollTop:$('#A').position().top}, 'slow');
    return false;
});

I also updated your sample to use the recommended syntax from jQuery 1.8+.

EDIT: As @Karl-Andre Gagnon points out:

return false work because it prevent the event from bubbling since preventDefault prevent the default action of the element. Since a click on a span has no default action, it does nothing!

So the first example will only really work if you're using something like

<a href="#" class="a">Back to top</a>




回答2:


You writted the "a" span like that :

<span class="a">A</spam>

Due to this typo, it is not closed. That's causing every click (on any letter) to be a click on the "a" after bubbling.

Just change the "m" for a "n" and everything work fine.

Those damn typos, messing up the entire code :)



来源:https://stackoverflow.com/questions/16504141/jquery-scrolltop-function-goes-to-correct-position-but-then-jumps-back-to-top-of

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