当链接被点击时如何滚动到一个元素

8
所以我有一个网站: http://www.gameplay-universe.uphero.com/ 您可以看到“跳转至内容”的链接。我希望当它被点击时页面滚动到
的位置。我正在使用最新版本的jQuery。如何实现这一点?

请搜索我的男人:https://dev59.com/d2w15IYBdhLWcg3wVaQa - tymeJV
4个回答

3

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

$(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();
});
});

那对我来说有效。


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

这将适用于 li 元素内的所有链接。

由于我对jQuery还很陌生,我应该编辑哪些变量才能使其在单击div#content onclick li.skip a时滚动? - PowerUser
$("#skip a").click(function(){ $('html, body').animate({ scrollTop: $("#content").offset().top }, 1000); return false; }); - ProllyGeek

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接