2015-02-06 53 views
1

我想一個類導航欄固定頂添加到導航當用戶滾動我做了這個腳本:加入JavaScript類一次槽滾動

var nav; 
function yScroll(){ 
    nav = document.getElementById('nav'); 
    yPos = window.pageYOffset; 
    if(yPos > 150){ 
     nav.className = nav.className + " navbar-fixed-top"; 
    } else { 
     nav.className = nav.className - " navbar-fixed-top"; 
    } 
} 
window.addEventListener("scroll", yScroll); 

但問題是,它總是會給出一個類NAV當yPos> 150時。

所以當我繼續在inspect元素中上下滾動時,它增加了很多相同的類。如何僅添加一次他的課程,或者您有其他解決方案。我有2個導航欄,我想在用戶滾動後只修復2個,所以他不能再看到最上面的一個。

回答

3

你使用jQuery所以要用:

nav.addClass("navbar-fixed-top") 

nav.removeClass("navbar-fixed-top") 

我想這也許你想要什麼:

var nav; 
function yScroll(){ 
    nav = $('#nav'); 
    yPos = window.pageYOffset; 
    nav.removeClass("navbar-fixed-top"); 
    if(yPos > 150){ 
     nav.addClass("navbar-fixed-top"); 
    } 
} 
window.addEventListener("scroll", yScroll); 
+0

正確,jQuery足夠聰明,只能添加一次類。 – 2015-02-06 12:39:11

+0

但爲什麼混合jQuery與非jQuery的JavaScript? – 2015-02-06 12:41:26

+0

當我在控制檯中向下滾動時,我看到越來越多的錯誤,Uncaught TypeError:undefined不是函數012main.js:5 Uncaught TypeError:undefined不是函數main.js:5 yScroll – 2015-02-06 12:42:44

2

檢查,如果它已經有像類這....

var nav; 
function yScroll(){ 
    nav = document.getElementById('nav'); 
    yPos = window.pageYOffset; 
    var isThereClass = nav.className.indexOf("navbar-fixed-top"); 
    if(yPos > 150 && isThereClass == -1){ 
     nav.className = nav.className + " navbar-fixed-top"; 
    } else if (yPos < 150 && isThereClass != -1) { 
     nav.className = nav.className - " navbar-fixed-top"; 
    } 
} 
window.addEventListener("scroll", yScroll);