2

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

我已经实现了滚动效果很好我只是不知道如何保持哈希 URL 以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);
    }
});
4

1 回答 1

2

我不知道您必须如何支持旧浏览器,否则您可以使用pushState 功能 该 url 提供有关如何使用它的文档 :)

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


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

// 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;
        });
    }
});
于 2013-07-22T17:35:11.587 回答