How to scroll page down after anchor navigation?

2019-08-15 05:15发布

问题:

I have added top menu as a div with position: fixed. It's placed in the top of the page, so it covers part of the content. I moved the layout down, so generally it's ok, BUT if user clicks any anchor link, the page scrolled to where the anchor is on top. But it's covered by the top menu. Is there a way to catch anchor event and process it with javascript (and jQuery if necessary)?

回答1:

You can use something like this:

$('a').click(function(){
    $('html').scrollTop($($(this).attr('href')).position().top + menu_height_offset)
})

To get the anchor position

$($(this).attr('href')).position().top

To make the offset related to the fixed menu

menu_height_offset

To make move the scroll

$('html').scrollTop()

http://api.jquery.com/scrollTop/

http://api.jquery.com/position/



回答2:

You need to calculate the offset of the element and sroll to the offset of element - height of the navigationbar - position:

$("a").on("click",function(){
    // height of the navigation bar
    var height= $("#nav").outerHeight();
    // position of the referenced dom-element
    var pos = $($(this).attr("href")).position().top;
    // scroll to the element
    $("body").scrollTop(pos - height);
    // suppress default
    return false;
})​

See it in action here.



回答3:

    /* START --- scroll till anchor */
        (function($) {
             $.fn.goTo = function() {
                  var top_menu_height=$('#div_menu_header').height() + 5 ;
                  //alert ( 'top_menu_height is:' + top_menu_height );
                  $('html, body').animate({
                        scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
                  }, 500);
                  return this; // for chaining...
             }
        })(jQuery);

        $(document).ready(function(){

          var url = document.URL, idx = url.indexOf("#") ;
          var hash = idx != -1 ? url.substring(idx+1) : "";

          $(window).load(function(){
             // Remove the # from the hash, as different browsers may or may not include it
             var anchor_to_scroll_to = location.hash.replace('#','');
             if ( anchor_to_scroll_to != '' ) {
                 anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
                 $(anchor_to_scroll_to).goTo();
             }
            });
        });
    /* STOP --- scroll till anchror */