简体   繁体   中英

How to scroll page down after anchor navigation?

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)?

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/

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 .

    /* 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 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM