滚动到锚点,同时保留哈希

Scroll to anchor whilst keeping the hash

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

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

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

我不知道你对旧浏览器的支持有多好,但除此之外,你可以使用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;
        });
    }
});