【问题标题】:How to scroll page down after anchor navigation?锚导航后如何向下滚动页面?
【发布时间】:2012-09-05 18:12:27
【问题描述】:

我已将顶部菜单添加为具有位置:固定的 div。 它位于页面顶部,因此它涵盖了部分内容。 我将布局向下移动,所以通常没关系,但是如果用户单击任何锚链接,页面将滚动到锚位于顶部的位置。但它被顶部菜单覆盖。 有没有办法捕获锚事件并使用 javascript(必要时使用 jQuery)处理它?

【问题讨论】:

  • 向我们展示您迄今为止的尝试。
  • 改写你的问题以强调这部分 - catch anchor event and process it

标签: javascript jquery html css anchor


【解决方案1】:

你可以这样使用:

$('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/

【讨论】:

  • 好吧,如果锚点是使用“名称”属性制作的,这将不起作用,但我已修复。一般来说,这会有所帮助,谢谢!
【解决方案2】:

你需要计算元素的偏移量并滚动到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;
})​

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2013-07-30
      • 2012-01-24
      相关资源
      最近更新 更多