简体   繁体   中英

How can I get my anchor link to scroll smoothly back up top like it does when it goes down?

I am trying to get my page to scroll back to my top anchor smoothly like it does when I go down to my bottom anchor. However instead of scrolling smoothly, it jumps without any animation.

Could someone assist me in pointing out what I can do to make it scroll smoothly both ways?

JavaScript

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 500);
    return false;
});

JSFiddle

<a href="#myAnchor" name="topAnchor" id="anchor1">的ID错误,将其设置为id="topAnchor" ,它将可以正常工作。

If you target the top anchor by id instead of by name, it will scroll smoothly. (It had an ID of anchor1 .) See the updated fiddle:

http://jsfiddle.net/freginold/atg8xcyd/1/

This is the updated HTML code for the top anchor element:

<a name="topAnchor" href="#myAnchor" rel="" id="topAnchor" class="anchorLink">Link to the anchor</a>

I have done this with JQuery. As a function it is reusable:

function goTo(goToElement) {
        $('body').animate({scrollTop:$(goToElement).offset().top}, 1500);
}

In any HTML element just set onclick="goTo('#id_to_goTo')" and it will smooth scroll to the element id you passed in either up or down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM