簡體   English   中英

錨定導航后如何向下滾動頁面?

[英]How to scroll page down after anchor navigation?

我添加了頂級菜單作為div位置:固定。 它位於頁面頂部,因此它涵蓋了部分內容。 我將布局向下移動,所以通常沒關系,但是如果用戶點擊任何錨鏈接,頁面會滾動到錨點位於頂部的位置。 但頂級菜單涵蓋了它。 有沒有辦法捕獲錨事件並使用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/

您需要計算元素的偏移量並滾動到offset of element - height of the navigationbaroffset of element - height of the navigationbar欄的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 */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM