2015-04-23 38 views
0

我知道這是一個重複的問題,但我試圖讓我的導航欄使用JavaScript/jQuery/CSS來改變樣式,通過使jQuery添加和刪除類取決於滾動條的位置,但沒有佔上風。我是jQuery的一個巨大的noob。有人能告訴我這些代碼有什麼問題嗎?我搜索了幾個小時,找不到和出錯。這是一個工作示例:http://codepen.io/anon/pen/QbWOJv 這裏是我的代碼:我不能讓我的導航在滾動更改

// on scroll, 
 
$(window).on('scroll',function(){ 
 

 
    // we round here to reduce a little workload 
 
    stop = Math.round($(window).scrollTop()); 
 
    if (stop > 50) { 
 
     $('.nav').addClass('passed-main'); 
 
    } else { 
 
     $('.nav').removeClass('passed-main'); 
 
    }
.nav 
 
      { 
 
       background-color: #000000; 
 
       opacity: 0.3; 
 
       width: 100%; 
 
       height: 40px; 
 
       position: fixed; 
 
       top: 0; 
 
       z-index: 2000; 
 
       transition: all 0.3s; 
 
      } 
 
      .nav.past-main 
 
      { 
 
       background-color: #ffffff; 
 
       opacity: 1; 
 
      }
<div class="nav"> 
 
     </div>

+2

我沒有看到你的榜樣任何問題。那麼你有什麼問題? – Kyojimaru

回答

1

或許例子是,你想實現的東西,當你用上面的代碼試試吧,它不是加工。

這裏是你的代碼片斷的問題:

  1. 你忘了關閉功能

    // on scroll, 
    $(window).on('scroll',function(){  
        // we round here to reduce a little workload 
        stop = Math.round($(window).scrollTop()); 
        if (stop > 50) { 
         $('.nav').addClass('passed-main'); 
        } else { 
         $('.nav').removeClass('passed-main'); 
        } 
    }); // You forgot to close the function here 
    
  2. 您添加/在你CSS你使用類中刪除passed-main類,而選擇器.nav.past-main

  3. 你的窗口沒有任何滾動條,所以你需要添加th是的CSS,以測試它是否工作

    body { 
        height: 1500px; 
    } 
    
  4. 你忘了,包括在片段中jQuery

這裏的工作更新片段

// on scroll, 
 
$(window).on('scroll', function() { 
 

 
    // we round here to reduce a little workload 
 
    stop = Math.round($(window).scrollTop()); 
 
    if (stop > 50) { 
 
     $('.nav').addClass('past-main'); 
 
    } else { 
 
     $('.nav').removeClass('past-main'); 
 
    } 
 
});
.nav { 
 
    background-color: #000000; 
 
    opacity: 0.3; 
 
    width: 100%; 
 
    height: 40px; 
 
    position: fixed; 
 
    top: 0; 
 
    z-index: 2000; 
 
    transition: all 0.3s; 
 
} 
 
.nav.past-main { 
 
    background-color: #ffffff; 
 
    opacity: 1; 
 
} 
 
body { 
 
    height: 1500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
 
<div class="nav"></div>

+0

謝謝你的幫助。我想這就是我的腦子關閉後得到的工作。 – mcpolo