jQuery 平滑滚动锚点并更新浏览器位置



我使用此代码在页面上的锚点之间平滑滚动,作为渐进式增强

$('a[href*=#]').click(function(e) {
    if (location.pathname.replace('/^//','') == this.pathname.replace('/^//','')
        && location.hostname == this.hostname) {
        var $target = $(this.hash);
        $target = $target.length && $target
            || $('[name=' + this.hash.slice(1) +']');
        if ($target.length) {
            $('.active').removeClass('active');
            $(this).parent().addClass('active');
            var targetOffset = $target.offset().top;
            $('html,body')
            .animate({
                scrollTop: targetOffset
            }, 750);
            e.preventDefault();
            //location.hash = $(this.hash);
        }
    }
});

我的问题是,有没有办法像往常一样更新浏览器中的 URL,但仍然可以流畅滚动?如果我取消注释最后一行,它将跳转到锚点,然后进行动画处理。

我刚刚在发布时解决了它。发布此内容以帮助他人。基本上,我只是在 animate 完成时使用回调来更新浏览器位置。

$('a[href*=#]').click(function(e) {
    if (location.pathname.replace('/^//','') == this.pathname.replace('/^//','')
        && location.hostname == this.hostname) {
        var hash = this.hash;
        var $target = $(this.hash);
        $target = $target.length && $target
            || $('[name=' + this.hash.slice(1) +']');
        if ($target.length) {
            $('.active').removeClass('active');
            $(this).parent().addClass('active');
            var targetOffset = $target.offset().top;
            $('html,body')
            .animate({
                scrollTop: targetOffset
            }, 750, function() {
                location.hash = hash;
            });
            e.preventDefault();
        }
    }

最新更新