滚动到锚点,同时保持哈希值

时间:2013-07-22 17:23:04

标签: javascript jquery html

我有一个导航到各个部分的页面。每个人都为该页面提供一个锚标记,以便有人可以轻松地重新访问该部分。我想要的是正常的机制正常工作,而不是跳转到该部分(按照正常的浏览器行为)我希望它滚动到那里。

我已经实现了滚动效果很好我只是不知道如何保持哈希网址e.preventDefault()阻止这种情况发生。如果我删除此行,则页面会在滚动之前闪烁。

$(".navigation a").click(function(e){
    $(".navigation a").removeClass("active");
    $(this).addClass("active");

    if ($(this).attr("href").substring(0,1) == "#"){
        e.preventDefault();

         $('html, body').animate({
             scrollTop: $($(this).attr("href")).offset().top
         }, 1000);
    }
});

1 个答案:

答案 0 :(得分:2)

我不知道您支持旧版浏览器有多好,但除此之外您可以使用pushState functionallity 该网址提供了有关如何使用它的文档:)

所有浏览器和IE10支持(所以没有9或更少)


无刷状态解决方案是滚动到适当的高度,然后更改网址。如果做得好,页面就不会跳:)

// you should change class navigation to id navigation, since there probally is only one
$(".navigation".find("a").click(function(e){ // with id this will speed up a bit
    //$(".navigation a").removeClass("active");
    $(".navigation a.active").removeClass("active"); // with A its faster
    $(this).addClass("active");
    var anchorDestination = this.href; // save for later, select as little times as possible

    //if ($(this).attr("href").substring(0,1) == "#"){
    if ( this.href.substring(0,1) == "#"){ // use native JS where possible
        e.preventDefault();
        var anchorDestination = this.href; // save for later
        var $aElem = $(this); // select it once, save it for later

        $('html, body').animate({
             //scrollTop: $($(this).attr("href")).offset().top
             scrollTop: $aElem.offset().top
        }, 1000, function(){
             window.location = anchorDestination;
        });
    }
});
相关问题