滚动页面到锚

Scroll Page to Anchor

本文关键字:滚动      更新时间:2023-09-26

我在一个我正在玩的网站上有一些锚,我希望他们滚动到锚,而不是突然跳到锚。我已经尝试了几个张贴的解决方案在这里的堆栈溢出,但还没有能够让他们的工作。我做错了什么吗?

我试过这个代码和几个类似的,但他们不工作:

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

该网站可以在这里找到,目前只有"关于我们"项目锚定:http://jsfiddle.net/pnKu2/

首先,不要选择所有的锚,你应该只选择你的导航IE:

$('.menu-hover-underline').click(function(){
    return false;
});

下一步扩展此功能以包含滚动

$('.menu-hover-underline').click(function(){
    var divId = $(this).text().toLowerCase();
    $('html, body').animate({
        scrollTop: $("#"+divId).offset().top
    }, 500);
    return false;
});

参见jsfiddle http://jsfiddle.net/pnKu2/2/

请注意,我更新了你的div id,因为除了aboutdiv是id="title"。

试试这个

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

你可以这样做:

$('a').click(function(e){
     var href = $(this).attr("href");
     var offsetTop = href === "#" ? 0 : $(href).offset().top;
     $('html, body').stop().animate(
     { 
       scrollTop: offsetTop
     }, 1000);
     e.preventDefault();
});