如何在单击链接时滚动到元素

How to scroll to an element when a link is clicked

本文关键字:滚动 元素 链接 单击      更新时间:2023-09-26

所以我有以下网站:http://www.gameplay-universe.uphero.com/

你可以看到"跳到内容"的链接。我想当它点击页面滚动到div#content。我使用的是最新版本的jQuery。我怎样才能做到这一点呢?

好的,这是我找到的解决方案:

$(document).ready(function() {
// Click event for any anchor tag that's href starts with #
$('a[href^="#"]').click(function(event) {
    // The id of the section we want to go to.
    var id = $(this).attr("href");
    // An offset to push the content down from the top.
    var offset = 60;
    // Our scroll target : the top position of the
    // section that has the id referenced by our href.
    var target = $(id).offset().top - offset;
    // The magic...smooth scrollin' goodness.
    $('html, body').animate({scrollTop:target}, 500);
    //prevent the page from jumping down to our section.
    event.preventDefault();
});
});

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

对于li元素中的所有链接都有效

$(document).scrollTop($('div#content').offset().top)

当我想要启用"scroll to"类型的Jquery效果时,我喜欢使用这个脚本。

http://cferdinandi.github.io/smooth-scroll/