Jquery 使用锚标记滚动 div 无法正常工作

Jquery Scroll on div using anchor tag is not Working properly

我添加了 jQuery 代码以使用锚标记在不同的 div 上滚动,滚动有效,但当它到达目标时 div 它会滚动回顶部页面的。这是我写的代码

$('a[href^="#"]').click(function(e) {
            e.preventDefault();
            var target = this.hash;
            var $target = $(target);
            $('html, body').animate({
                'scrollTop': $target.offset().top - 160
            }, 1000).stop();
        });

有什么建议吗?

你可以这样做:

$(document).ready(function(){
    $("a").on('click', function(event) {
        if (this.hash !== "") {
            event.preventDefault();
            var hash = this.hash;
            $('html, body').animate({
                scrollTop: $(hash).offset().top
            }, 800, function(){
                window.location.hash = hash;
            });
        }
    });
});