如何在定位导航后向下滚动页面

How to scroll page down after anchor navigation?

本文关键字:滚动 定位 导航      更新时间:2023-09-26

我添加了顶部菜单作为div,位置为:fixed。它被放置在页面的顶部,因此它覆盖了部分内容。我把布局向下移动了,所以一般来说是可以的,但如果用户点击任何锚链接,页面就会滚动到锚在顶部的位置。但它被顶级菜单覆盖了。是否有一种方法可以捕获锚点事件并使用javascript(必要时还可以使用jQuery)进行处理?

您可以使用这样的东西:

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

获取锚位置

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

使偏移与固定菜单相关

menu_height_offset

移动滚动

$('html').scrollTop()

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

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

您需要计算元素和sroll到offset of element - height of the navigationbar-位置的偏移量:

$("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;
})​

请在此处查看它的实际操作

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