How to scroll page down after anchor navigation?

依然范特西╮ 提交于 2020-01-05 06:31:27

问题


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


来源:https://stackoverflow.com/questions/12287376/how-to-scroll-page-down-after-anchor-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!