javascript 如何使用 jquery 为网页上下滚动动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22282408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:50:31  来源:igfitidea点击:

How to animate scroll down and up the webpage using jquery

javascriptjqueryhtmlcssscroll

提问by ray

Here is jquery i got from stackoverflow as well.

这也是我从 stackoverflow 得到的 jquery。

$('ul.navigation').find('a').click(function(){
    var $href = $(this).attr('href');
    var $anchor = $('#'+$href).offset();
    $('body').animate({ scrollTop: $anchor.top });
    return false;
});

Here is my nav

这是我的导航

<ul class="navigation">
    <li><a href="#" class="home selected">HOME</a></li>
    <li><a href="#aboutMe" class="aboutMe">ABOUT ME</a></li>
    <li><a href="#services" class="services">SERVICES</a></li>
    <li><a href="#portfolio" class="portfolio">PORTFOLIO</a></li>
    <li><a href="#something" class="something">SOMETHING TO READ</a></li>
    <li><a href="#contactMe" class="contactMe">CONTACT ME</a></li>
</ul>

It jumps on the correct id but it does animate. Animation part is what I'm missing. Thanks in advance!

它跳转到正确的 id 但它确实有动画。动画部分是我所缺少的。提前致谢!

回答by

If I understand correctly, this is what you're looking for:

如果我理解正确,这就是您要查找的内容:

$(document).ready(function() {
    $('ul.navigation').on('click', 'a', function(e) {       
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top
        }, 500);
    });
});