2015-05-08 19 views
1

我有以下問題。我想要的是,當用戶點擊「聯繫人」上的導航欄時,它將鏈接到聯繫人頁面。這是一個單一頁面。當您聯繫並點擊頁面底部時,例如「Over ons」,它應該重定向到主頁(單頁)並停在該部分。這是有效的,但是當你來自另一個頁面時,當前部分與標題重疊。從另一個頁面出來時段會被標題重疊

只有當您在index.html內進行導航時,jQuery代碼纔會使用標題的偏移量。

有沒有辦法解決這個問題,所以該部分不會被頭部重疊?

活生生的例子:

http://codepen.io/anon/pen/NqxxQd

jQuery代碼:

// An offset to push the content down from the top 
    var offset = $('#header').outerHeight(); 

    $('#primary-navwrapper li:not(.prev-page, .next-page), .list-of-links li').find('a[href^="#"]').click(function(event) { 
     event.preventDefault(); 


     $('#primary-navwrapper li a').removeClass("current"); 
     $(this).addClass("current"); 

     var anchorId = $(this).attr("href"); 
     var target = $(anchorId).offset().top - offset;   


     $('html, body').animate({ scrollTop: target }, 500, function() { 
      window.location.hash = anchorId;   
     }); 

    }); 



    function setActiveListElements(event){ 
     // Get the offset of the window from the top of page 
     var windowPos = $(window).scrollTop(); 

     $('#primary-navwrapper li a[href^="#"]').each(function() { 
      var anchorId = $(this); 
      var target = $(anchorId.attr("href")); 

      var offsetTop = target.position().top - offset; 

      if (target.length > 0) { 

       if (target.position().top - offset <= windowPos && (target.position().top + target.height() + offset) > windowPos) { 

        $('#primary-navwrapper li a').removeClass("current"); 
        anchorId.addClass("current"); 
       } 
      } 

     }); 

    } 

$(window).scroll(function() { 
     setActiveListElements(); 
     //updateLocationHash(); 
    }); 
+0

我們不能去「聯繫」頁面,從您的代碼鋼筆。 – krillgar

+0

這是聯繫頁面http://codepen.io/anon/pen/RPrabw的codepen。它適用於我,當你點擊頂部導航欄中的「contact」。如果它不工作,讓我知道! @krillgar – Caspert

+0

@Caspert該例中沒有頂部導航。 – newmediafreak

回答

1

您的代碼向下滾動到每個部分需要被放置在它自己的函數調用的東西像懂事FireActiveElement。給它一個通過anchorId字符串發送的參數。您的點擊偵聽器然後需要調用該函數。

所以,你有類似的功能:

function FireActiveElement(anchorId) { 
    var target = $(anchorId).offset().top - offset; 

    $('html, body').animate({ 
     scrollTop: target 
    }, 500, function() { 
     window.location.hash = anchorId; 
    }); 
} 

然後,你可以做的是這樣的:

function CheckHash() { 
    if (window.location.hash) { 
     FireActiveElement(window.location.hash); 
    } 
} 

然後,你需要添加功能回調你的身體淡入:

$('body').fadeIn(500, CheckHash); 

很難測試這個工程我自己,但希望可以幫助你。

P.S.

如果你需要有那些在網頁加載時發射更多的東西,你可能要稍微改變fadeIn喜歡的東西:

$('body').fadeIn(500, function() { 
    CheckHash(); 
    // Examples: 
    SomeOtherFunction(); 
    FireMeOnPageLoad(); 
}); 
+0

沒問題!我感謝你的回答:)我應該在我的點擊功能裏面調用FireActiveElement嗎? – Caspert

+0

@Caspert是的:) - 「_您的點擊偵聽器,然後需要調用該函數。」 –

+1

@Caspert剛剛意識到有一個CheckHash函數的錯誤,所以我已經更新。 –

相關問題