问题
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