2013-05-13 65 views
1

http://jsfiddle.net/5Cfm6/1/jQuery的滾動,改變導航活動類的頁面滾動搞砸了,並使錯誤的鏈接活動?

所以每當我點擊的手錶,它會與視頻的股利,但如果我點擊導航欄上的其他環節,有時突出主用鏈路,它總是在錯誤的鏈接。例如,如果我點擊左右,它會突出顯示鏈接。有人可以幫我把它突出顯示我目前正在使用的正確的div嗎?

這是我到目前爲止。

$(window).scroll(function() { 
    var windscroll = $(window).scrollTop(); 
    if (windscroll >= 100) { 
     $('.container div').each(function (i) { 
      if ($(this).position().top <= windscroll - 20) { 
       $('nav a.active').removeClass('active'); 
       $('nav a').eq(i).addClass('active'); 
      } 
     }); 
    } else { 
     $('nav a.active').removeClass('active'); 
     $('nav a:first').addClass('active'); 
    }`enter code here` 

}).scroll(); 

回答

2

我想指出(至少在你的小提琴中)「贊助商」div之外的div.container,所以它可能不適用於贊助商(例如,如果您在「贊助商」之後添加更多部分),即使現在意外地發生了這種情況,您將來也可能遇到其他意想不到的問題。

所以,你必須爲你的代碼(不不期而遇)做正常工作是什麼:

  1. 放置div.container的「贊助商」 div內。
  2. 變化:
    $('.container div').each(function (i) {
    $('.container > div').each(function (i) {
  3. 變化:
    if ($(this).position().top <= windscroll + 20) {
    if ($(this).position().top <= windscroll + 34) {
    因爲這是scrollTop偏移你在4號線(scrollPoint = $('...').offset().top - 34)設置。

Working demo可以在這裏找到。

編輯: 最後一個情況下,你可能要解決的是在最後一節的高度比當前窗口高度較小,所以這是不可能的scrollTop永遠到達最後一節的position().top。在這種情況下,當用戶一直滾動到底部時,高亮導航欄中的最後一個元素仍然是有意義的。這可以通過這個小加來實現:

$(window).scroll(function() { 
    ... 
    var fromBottom = $(document).height() 
        - ($(window).scrollTop() + $(window).height()); 
    if (fromBottom == 0) {  // <-- scrolled to the bottom 
     $('nav a.active').removeClass('active'); 
     $('nav a:last').addClass('active'); 
    } else if ... 

(該working demo已更新,以說明這一點。)

(注:不相關的當前問題,但你可能想代替<br/> :)

+0

謝謝,我剛剛意識到,當我在贊助商後添加更多div時,我的代碼停止工作,謝謝您指出sponser div位於容器外部!解決了我的問題!!!!!!!!!!!!! – ZZPLKF 2013-05-13 08:32:25

+0

我也注意到在你的第二個小提琴(你刪除的那個)中,你有'windscroll-34',當它應該是'windscroll + 34'。另外,如果(windscroll> = 100){'to'if(windscroll> 34){',爲了正確識別「watch」部分,您也可以在我的答案中看到提及的工作演示,該演示已更新爲包含此更改。總是很樂意幫忙;) – gkalpak 2013-05-13 08:36:31

+0

非常感謝!我無法告訴你我多麼感激!這是我到目前爲止:) http://www.wearanopenheart.com/test/再次感謝你! – ZZPLKF 2013-05-13 08:42:55

0

嘗試目標的.container格,而不是每一個後裔直接孩子,以及你需要通過1增加i的價值,因爲它是基於0:

$('.container > div').each(function (i) { 
    var index = i + 1; 
    if ($(this).position().top <= windscroll - 20) { 
     $('nav a.active').removeClass('active'); 
     $('nav a').eq(index).addClass('active'); 
    } 
}); 

Updated Fiddle

+0

謝謝代碼/答案!,它現在工作完美! – ZZPLKF 2013-05-13 06:34:04