Div anchors scrolling too far

后端 未结 5 1561
旧巷少年郎
旧巷少年郎 2020-12-25 11:53

I\'m using a static bar at the top of my site, about 20px high. When I click an anchor link(for those who don\'t know, the navigation on wikipedia works like that. Click a t

5条回答
  •  难免孤独
    2020-12-25 12:10

    I had the same problem. Here's a jQuery solution

    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = this.hash;
        var $trget = $(target);
        // Example: your header is 70px tall.
        var newTop = $trget.offset().top - 70; 
        $('html, body').animate ({
            scrollTop: newTop
        }, 500, 'swing', function () {
            window.location.hash = target;
        }); 
    });
    

提交回复
热议问题