锚定导航后如何向下滚动页面?

时间:2012-09-05 18:12:28

标签: javascript jquery html css anchor

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

3 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

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

答案 1 :(得分:1)

您需要计算元素的偏移量并滚动到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

答案 2 :(得分:0)

    /* 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 */
相关问题