Fixed page header overlaps in-page anchors

前端 未结 30 2855
逝去的感伤
逝去的感伤 2020-11-22 00:25

If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:

Is there a way to use the URL anchor (the #fragment part) t

30条回答
  •  青春惊慌失措
    2020-11-22 00:34

    Here is a complete jquery solution that will work in IE:

    Suppose the navigation bar elements are something like this:

    
    

    You can use the following jquery snippet to offset the scroll:

    $(function() {
        $("a.navigation").click(function(event) {
            event.preventDefault();
            offSetScroll($(this));
        });
        offSetScrollFromLocation(window.location.href.toLowerCase());
    });
    
    function offSetScroll(anchor) {
        var href = anchor.attr("href");
        offSetScrollFromLocation(href);
    }
    
    function offSetScrollFromLocation(href) {
        //Change this according to the height of the navigation bar
        var fromTop = 250;
        if(href.indexOf("#")<=0)
            return;
        var hash=href.substring(href.indexOf("#"));
        var targetOffset = $(hash).offset().top-fromTop;
        $('html, body').animate({scrollTop: targetOffset}, 400, function(e) {
    
        });
    }
    

提交回复
热议问题