Fixed page header overlaps in-page anchors

前端 未结 30 2802
逝去的感伤
逝去的感伤 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:56

    While some of the proposed solutions work for fragment links (= hash links) within the same page (like a menu link that scrolls down), I found that none of them worked in current Chrome when you want to use fragment links coming in from other pages.

    So calling www.mydomain.com/page.html#foo from scratch will NOT offset your target in current Chrome with any of the given CSS solutions or JS solutions.

    There is also a jQuery bug report describing some details of the problem.

    SOLUTION

    The only option I found so far that really works in Chrome is JavaScript that is not called onDomReady but with a delay.

    // set timeout onDomReady
    $(function() {
        setTimeout(delayedFragmentTargetOffset, 500);
    });
    
    // add scroll offset to fragment target (if there is one)
    function delayedFragmentTargetOffset(){
        var offset = $(':target').offset();
        if(offset){
            var scrollto = offset.top - 95; // minus fixed header height
            $('html, body').animate({scrollTop:scrollto}, 0);
        }
    }
    

    SUMMARY

    Without a JS delay solutions will probably work in Firefox, IE, Safari, but not in Chrome.

提交回复
热议问题